Fanning Software Consulting

Packing Floats into a Byte Array

QUESTION: I would like to pack floating point values into a byte array for transfer over a network connection. Can you show me how to pack these floating point values into a byte array and then unpack the byte array back to floats on the other side?

ANSWER: Sure, this can be done with the Byte and Float functions in IDL. Consider the following floating point number array.

   IDL> f = [2453.345, 9483.239, 4923.127]

To convert these three values to a byte array, you would do this.

   IDL> b = Byte(f, 0, 4, 3)

The numbers in the Byte function signify the offset into the floating point array (0, in this case), the fact that there are four bytes in a floating point value, and that there are three values required. The result will be a 4x3 byte array. Each row of the byte array will represent a number, represented as a four-byte vector.

For example, the number 2453.345 is represented by the four-element byte array [133,85,25,69].

   IDL> Print, b[*,0]
        133  85  25  69

To turn these byte array values back into floats, you use the Float function.

   IDL> Print, Float(b, 0, 3), Format='(3(F0.3,2x))'
      2453.345  9483.239  4923.127

Note that byte order may play a role if you are transferring these between different machines, depending upon the endian nature of the machine where the byte array is packed and the machine that unpacks the byte array. You may have to take advantage of the ByteOrder command and one of its many keywords to get the byte order right.

Version of IDL used to prepare this article: IDL 7.0.1.

Last Updated: 2 June 2011