3 ms·
The problem happens if you do uint64_t = uint8_t << 24, for example. The shift will promote the uint8_t to int (not unsigned int), and then the conversion to ui
by moefh 9y ago
The problem happens if you do uint64_t = uint8_t << 24, for example. The shift will promote the uint8_t to int (not unsigned int), and then the conversion to uint64_t will sign extend, so
uint8_t u8 = 255;
uint64_t u64 = u8 << 24;
printf("%016llx\n", (long long) u64);
prints "ffffffffff000000". If you instead do
uint64_t u64 = (uint64_t) u8 << 24;
or
uint64_t u64 = (uint32_t) u8 << 24;
It prints "00000000ff000000" as most people expect. (I think the second example with (uint32_t) will only work if "int" is at most 32 bits, but I might be wrong).
- baby 9y agofor anyone who wants to run that themselves: #include <stdio.h> #include <stdint.h> int main(){ uint8_t start = -1; printf("%x\n", start); // prints 0xff uint64_t result = start << 24; printf("%llx\n", result); // should print 00000000ff000000, but will print ffffffffff000000 result = (uint64_t)start << 24; printf("%llx\n", result); // prints 00000000ff000000 return 0; }