Nathaniel Nathaniel - 14 days ago 5
C Question

Convert byte array to unsigned int using pointers

char* f = (char*)malloc(4 * sizeof(char));
f[0] = 0;
f[1] = 0;
f[2] = 0;
f[3] = 1;
unsigned int j = *f;
printf("%u\n", j);


so if the memory looks like this:
0000 0000 0000 0000 0000 0000 0000 0001

The program outputs 0.
How do I make it output a uint value of the entire 32 bits?

Answer

Because you are using type promotion. char will promote to int when accessed. You'll get no diagnostic for this. So what you are doing is dereferencing the first element in your char array, which is 0, and assigning it to an int...which likewise ends up being 0.

What you want to do is technically undefined behavior but generally works. You want to do this:

unsigned int j = *reinterpret_cast<unsigned int*>(f);

At this point you'll be dealing with undefined behavior and with the endianness of the platform. You probably do not have the value you want recorded in your byte stream. You're treading in territory that requires intimate knowledge of your compiler and your target architecture.

Comments