I want to use the higher half of an integer to store some value. Now out of the higher half, i want to again store two different values as below.
If long
is 32 bits, i want to use first 8 bits and the next 8 bits(from left).
If long
is 64 bits, i want to use first 16 bits and the next 16 bits(from left).
I have come up with something like below.
unsigned long foo;
unsigned long bar = 1UL; // i'll ensure this value fits in 2 bits to handle 16 bits integer.
unsigned long baz = 1UL; // i'll ensure this value fits in 2 bits.
int BitsInLong = CHAR_BIT * sizeof(unsigned long);
foo |= bar << (BitsInLong / 2 + BitsInLong / 4);
foo |= baz << (BitsInLong / 2);
Though this seems to work, are there some situations where this can fail or may be is there a better solution.