3 ms·
is it doing a sign extension though? If it promotes without adding a bunch of 1s it should be fine.
by baby 9y ago
is it doing a sign extension though? If it promotes without adding a bunch of 1s it should be fine.
- masklinn 9y agoIt's probably the latter part (conversion to "whatever the expression's type ends up being) doing the sign-extension, see moefh's sibling comment with a uint64_t final destination, the int -> uint64_t is sign-extending. I should have quoted the proper part I was replying to ("I don't think you're talking about integer promotion here")
- baby 9y agoI just checked that myself, it is not the casting to uint64_t since the sign-extension happens even before that. The problem is that the result from the shift is stored in a register, which is probably 64-bit on your machine, and to do that it is sign extended from a signed int to a signed 64-bit value. Wrote more about that here: https://www.cryptologie.net/article/418/integer-promotion-in-c/ https://www.cryptologie.net/article/418/integer-promotion-in...
- pm215 9y agoThe size of the cpu registers don't matter here. What matters is that 'int' is a bigger type than uint8_t and smaller than uint64_t: the resulting unexpected behaviour is mandated by the C standard regardless of the register size of the cpu (for instance both 32-bit i386 and 64-bit x86_64 will behave the same, because both typically have 32 bit 'int'). More generally, reasoning about this kind of thing by thinking about the CPU leads you down the wrong path -- modern C as implemented by compilers today is an implementation of a standardized language, and they behave as that standard says, which is not always as you might expect from the hardware behaviour. (Simple example: left shifting of negative numbers does a simple straightforward thing on practically all hardware, but the C spec says it's UB and if you write code that assumes the h/w behaviour you'll get bitten.)
- baby 9y agoEven if the code would still be bad for 32-bit machines, I'm not sure they would suffer from the bug (if they had 32-bit signed int as well). 1. Your uint8_t would get promoted to a 32-bit int 2. Your int would get shifted, getting a 1 in the signing bit 3. The result would get stored in a uint32_t when being casted Now I don't know how uint64_t works on a 32-bit machine, I'd have to compile the C code with -m32 to see. EDIT: just tested and you're right, it's still a problem on 32-bit machines.