The C language guarantees that any value of any type¹ can be obtained as an array of bytes. Byte type unsigned char . Here's a low-level way of copying a float into an array of bytes. sizeof(f) - the number of bytes used to store the value of the variable f ; you can also use sizeof(float) (you can pass sizeof variable or a more complex expression or its type).
float f = 0.6; unsigned char data[sizeof(float)]; size_t i; for (i = 0; i < sizeof(float); i++) { data[i] = (unsigned char*)f + i; }
The memcpy or memmove do exactly that (or its optimized version).
float f = 0.6; unsigned char data[sizeof(float)]; memcpy(data, f, sizeof(f));
You do not even need to make this copy. You can directly pass a pointer to a float to the write-to-USB function and specify how many bytes to copy ( sizeof(f) ). You will need an explicit conversion if the function takes a pointer argument other than void* .
int write_to_usb(unsigned char *ptr, size_t size); result = write_to_usb((unsigned char*)f, sizeof(f))
Please note that this will only work if the device uses the same representation of floating point numbers, which is common but not universal. Most machines use IEEE floating point formats, but you may need to switch the principle.
As for your incorrect attempt: the >> operator works with integers. In the expression (int) f >> 24 , f cast to int ; if you wrote f >> 24 without translation, f will still be automatically converted to int . Converting a floating point value to an integer approximates it by trimming or rounding it (usually in the direction of 0, but the rule depends on the platform). 0.6, rounded to an integer, is 0 or 1, so data[0] is 0 or 1, and the rest is 0.
You need to act on the bytes of the float, and not on its value.
¹ The exception of functions that actually cannot be manipulated in C, but including pointers to functions whose functions automatically decompose. Sub>
Gilles
source share