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 how do I know how large it is, and how is it represented in hex?
The hex-represenation is needed because I may need to switch the lower and upper nibbles.
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
unionoffloatordoubleand an appropriate-length array ofunsigned char. Store the float value into the union and then retrieve theunsigned charbytes for conversion to hex. You can also use casts of the appropriate pointer types to perform this “aliasing”.For Java users, where unions and aliasing are not an option, there are these class methods on Float and Double:
And their inverses
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.