For unpacking complex binary strings with mixed doubles and integers using Ruby's String.unpack I need to determine offsets within the binary string. Commonly, doubles are 8 bytes and integers are 4 bytes, but in order to make my code machine-independent, I would like to query these sizes from within my Ruby code.
What is the easiest way to determine the size of integers and doubles from within Ruby, i.e., request the response of a request to C's sizeof( type )
method?
I have found a workable solution, by using Array#pack
, the inverse method of String#unpack
. By packing a string of 1 integer or 1 double it is possible to determine the size of integers and doubles from within ruby itself which gives the same results as using sizeof(int)
or sizeof(double)
(because of the implementation of Array#pack
in C):
[1.to_i].pack("i").size # 4
[1.to_f].pack("d").size # 8