I have a count register, which is made up of two 32-bit unsigned integers, one for the higher 32 bits of the value (most significant word), and other for the lower 32 bits of the value (least significant word).
What is the best way in C to combine these two 32-bit unsigned integers and then display as a large number?
In specific:
leastSignificantWord = 4294967295; //2^32-1
printf("Counter: %u%u", mostSignificantWord,leastSignificantWord);
This would print fine.
When the number is incremented to 4294967296, I have it so the leastSignificantWord wipes to 0, and mostSignificantWord (0 initially) is now 1. The whole counter should now read 4294967296, but right now it just reads 10, because I'm just concatenating 1 from mostSignificantWord and 0 from leastSignificantWord.
How should I make it display 4294967296 instead of 10?
Best Answer
It might be advantageous to use unsigned integers with explicit sizes in this case:
Output4294967296
Break down of
(uint64_t) mostSignificantWord << 32 | leastSignificantWord
(typename)
does typecasting in C. It changes value data type totypename
.(uint64_t) 0x00000001 -> 0x0000000000000001
<<
does left shift. In C left shift on unsigned integers performs logical shift.0x0000000000000001 << 32 -> 0x0000000100000000
|
does 'bitwise or' (logical OR on bits of the operands).0b0101 | 0b1001 -> 0b1101