Assign large type variable to a smaller types array

1.2k views Asked by At

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.

2

There are 2 answers

1
phuclv On BEST ANSWER

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;
5
Some programmer dude On

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.