Question

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.

Was it helpful?

Solution

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;

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top