문제

I am just wondering how this works, and to be clear as to whether it actually does work.

If you have a 32 bit int and an 8 bit int array of size 4. Can you assign the 32 bit int to the 0th index in the 8 bit int array and effectively have the same value, bit wise. Also if you then wanted to convert it back I presume you could fill up the 32 bit int with the array and appropriate bit shifts.

int32 bigVbl   = 20;
int8  smallVbl[4];

smallVbl[0] = bigVbl;

I expect the smallVbl array to hold the entirety of bigVbl.

도움이 되었습니까?

해결책

Assignments always truncate the most significant bits and retain the LSBs. Other arithmetics operations truncate the result too, if it overflows. In that way you can extend the maths (and many other operations) for operating on big integers easily. Without truncation how can you crammed 32 bits into 8 bits?

To copy the 32-bit int into an array of 4 8-bit chars, the easiest ways is copy the whole number into the array. Another way is assign element-by-element

smallVbl[0] = bigVbl & 0xff; // the & 0xff is not really needed
smallVbl[1] = (bigVbl >> 8) & 0xff;
smallVbl[2] = (bigVbl >> 16) & 0xff;
smallVbl[3] = (bigVbl >> 24) & 0xff;

다른 팁

There are a couple of ways of doing it, the simplest probably being to use std::copy_n to copy the integer into the array:

std::copy_n(reinterpret_cast<int8*>(&bigVbl),           // Source to copy from
            std::min(sizeof(smallVbl), sizeof(bigVbl)), // Number of bytes to copy
            smallVbl);                                  // Destination to copy to

To copy the opposite direction, just switch place of the source and destination in the above call.

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