4x8 bit int to 32 bit integer
I have
_int8 arr[0] = 0;
_int8 arr[1] = 0;
_int8 arr[2] = 14;
_int8 arr[3] = 16;
I need to convert it to one _int32 using as arr[0] as first par开发者_高级运维t <..> and arr[3] as last. In the end it should be
_int32 back = 3600;
Should I use bit shifts or smth like that to achieve this?
Cast them all to int
then use:
(arr[0] << 24) | (arr[1] << 16) | (arr[2] << 8) | arr[3]
Alternatively:
_int32 back = 0;
for (int i = 0; i < 4; ++i)
back = (back << 8) | arr[i];
If you know the byte ordering (i.e. big endian or little endian, check it out on wikipedia), and the array is set up in the right order you can just do:
back = *(_int32 *)arr;
That'll just interpret your array of 4 bytes as a buffer holding a single 32-bit integer. In your example though, I think you've got it set up for big endian and x86 isn't. So you'd need to swap some bytes.
For instance:
_int32 back = arr[0] << 24 | arr[1] << 16 | arr[2] << 8 | arr[3];
or something like that.
It's probably my SCO compiler but I think I've had problems if I didn't use (arr[0]&0xff) and so forth for doing the shifts. Certainly doesn't hurt anything.
精彩评论