Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float to char array

Tags:

arrays

c

As a 55-year-old newcomer to programming, there is one point I can't understand in floats.

Let's say I have a float like

float my_fl = 1.00f

When I want to store this value in a char array I can simply use memcpy

char  bytes[4];

memcpy(bytes, &my_fl, sizeof(float));

for (size_t i = 0; i < sizeof(float); ++i)
    printf("Byte %zu is 0x%02x.\n", i, bytes[i]);

I want to print this array to console, but I see different values instead of 0x3f800000

Can you help me where I went wrong?

like image 239
eLigt Avatar asked Dec 05 '25 02:12

eLigt


1 Answers

Running this code gives the following output:

Byte 0 is 0x00.
Byte 1 is 0x00.
Byte 2 is 0xffffff80.
Byte 3 is 0x3f.

Because you're using char to store the bytes, and on your system (and most in fact) a char is signed. Then when a char is passed to printf which is a variadic function, a value of type char is promoted to type int.

In the case of byte 2 which contains the representation 0x80, this representation as a signed char has the value -128. When promoted to a int, you still have the value -128 but its representation is 0xffffff80 which is what gets printed with %x.

If you change the type of bytes to unsigned char, the values in the array will all be positive regardless of the representation, so there will be no sign extension when the values are promoted.

like image 179
dbush Avatar answered Dec 07 '25 15:12

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!