Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use a bit mask when truncating uint64_t to uint8_t[i]?

If I have a large int, say a uint64_t, and an array of uint8_t, e.g.:

uint64_t large = 12345678901234567890;
uint8_t small[5];

and I want to copy the 8 least significant bits of the uint64_t into an element of the array of uint8_t, is it safe to just use:

small[3] = large;

or should I use a bit-mask:

small[3] = large & 255;

i.e. Is there any situation where the rest of the large int may somehow overflow into the other elements of the array?

like image 526

1 Answers

It will most certainly not cause data to be processed incorrectly. However, some compilers may generate a warning message.

There are two options to avoid these.

You can cast your variable:

(uint8_t)large

Or you can disable the warning:

#pragma warning(disable:4503)

I would suggest casting the variable, because hiding compiler warnings will potentially keep you from spotting actual problems and is therefore not best practice.

like image 167
bytecode77 Avatar answered Oct 09 '22 05:10

bytecode77