I often use 64-bit integers to store aggregate values to be stored on disk.
Suppose I use the last 8-bits of a 64-bit integer to store some value from 0 to 255. Then suppose I want to increment that value, without affecting the rest of the 64 bit integer.
This could be done in 2 ways. I could use bitwise operations like this:
val = (val & (0xFFUL << 56)) + (1UL << 56) | (val & 0xFFFFFFFFFFFFFFUL);
Or I could simply address the last byte directly and increment it:
++(*( ((unsigned char*) &val) + 7));
The latter method is probably more efficient, but is it portable and safe? As far as I can see, this should be fine on both big and little endian computers, and also should not cause any alignment issues because I am addressing a single byte. Still, I'm not sure. Am I correct? Is the latter method portable/safe?