It isn't clear what type variable
is. Without that specified, we can only speculate.
But in general, you should avoid bit shifting on signed integer types, as that leads to various forms of poorly-defined behavior. This in turn means that you have to be careful with small integer types too, because they get promoted to signed int
. See Implicit type promotion rules.
The specific case of (uint8)((variable >> 8) & 0xFFu);
is safe if variable
is unsigned. Otherwise it is unsafe, since right-shifting a negative value leads to implementation-defined behavior (arithmetic or logical shift).
variable << 8
will invoke undefined behavior on 16 bit systems in case variable
is a small integer type, or an int16_t
.
The safest, most portable way no matter left/right shift is therefore this:
chunk_lsb = variable;
chunk_msb = ((unsigned int)variable >> 8);
Though you might want to be overly explicit in order to silence all compiler warnings:
chunk_lsb = (uint8_t) (variable & 0xFFu);
chunk_msb = (uint8_t) ( (unsigned int)variable>>8 & 0xFFu );