Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Float to char array

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading