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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With