5 ms·
There's no sign-extension involved. Let's say the input is (uint8_t)128. This gets promoted to (int)128, which is then shifted 24 bits to the left. If the input
by pbsd 9y ago
There's no sign-extension involved. Let's say the input is (uint8_t)128. This gets promoted to (int)128, which is then shifted 24 bits to the left. If the input was (int8_t)128, it would get sign-extended into (int)-128, but that is not the case here.
With 32-bit ints, this operation will result in 0x80000000, shifting a bit into the sign bit, which constitutes an overflow (and undefined behavior). Think about it in terms of multiplication: you're multiplying a positive integer by 2^24, and it turns out negative!
- baby 9y agoright, but he only used unsigned types. I think there is another problem here: u64 = u8 << 24 Here the integer promotion might transform u8 into a 16-bit or 32-bit int (depending on the arch). Which will then be converted to a u64 AFTER the shift. Which might have you lose half or more of the bits. His code is not that though, it's u32 = u8 << 24 which should work only if ints are 32-bit on the system you compile on.
- pbsd 9y agou8 gets promoted to signed int before the shift. That he only used unsigned types is irrelevant.