I am transferring data over to a slave device from an iPhone where the transmission requires a 16 bit data value. Now I have a floating-point value that I need to transfer, but
If you want to know the details, look up the IEEE floating-point standard on the web. But to represent it in hex, simply generate the number, obtain the individual bytes, and generate their hex representation. The two things you need to know are the length of the value (eg, sizeof(double)
) and whether it's stored "big-endian" or "little-endian". iOS devices are always "little-endian", meaning that the least-significant byte of the value has the lowest memory address.
A straight-forward way to obtain the bytes is to create a C union
of float
or double
and an appropriate-length array of unsigned char
. Store the float value into the union and then retrieve the unsigned char
bytes for conversion to hex. You can also use casts of the appropriate pointer types to perform this "aliasing".
union {
float f;
double d;
unsigned char c[8];
} foo;
foo.d = 3.14156;
for(int i=0;i<8;i++) printf("%02X",foo.c[i]);
For Java users, where unions and aliasing are not an option, there are these class methods on Float and Double:
Float.floatToRawIntBits(floatValue)
Double.doubleToRawLongBits(doubleValue)
And their inverses
Float.intBitsToDouble(intValue)
Double.longBitsToDouble(longValue)
Note that these do not do a cast-like conversion (4.1 float will not be converted to 4 int, eg), but instead they transfer the bit patterns unchanged from float to integer formats.