Alex Rivera | Logout

Convert 4 bytes char to int32 in C

Asked 2011-11-17T19:24:40.300
20

I first convert an int32 number to char[4] array, then convert the array back to int32 by (int *), but the number isn't the same as before:

unsigned int num = 2130706432;
unsigned int x;
unsigned char a[4];

a[0] = (num>>24) & 0xFF;
a[1] = (num>>16) & 0xFF;
a[2] = (num>>8) & 0xFF;
a[3] = num & 0xFF;

x = *(int *)a;
printf("%d\n", x);

the output is 127. And if I set num = 127, the output is 2130706432. Does anyone have ideas?

c
Edit
Report

1 Answer

6

This line is never going to work correctly on a little-endian machine:

x = *(int *)a;

You need to unpack the data before you print out the value.

answered 2011-11-17T19:30:42.600

Your Answer