문제

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 part <..> 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?

도움이 되었습니까?

해결책

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.

다른 팁

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];

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top