Learning the hard way, I tried to left shift a long long and uint64_t to more than 32 bits on an x86 machine resulted 0. I vaguely remember to have read somewhere than on a 32 bit machine shift operators only work on the first 32 bits but cannot recollect the source.
I would like to know is if Shifting more than 32 bits of a uint64_t integer on an x86 machine is an Undefined Behavior?
Learning the hard way, I tried to left shift a long long and uint64_t
Share
The standard says (6.5.7 in n1570):
Shifting a
uint64_ta distance of less than 64 bits is completely defined by the standard.Since
long longmust be at least 64 bits, shiftinglong longvalues less than 64 bits is defined by the standard for nonnegative values, if the result doesn’t overflow.Note, however, that if you write a literal that fits into 32 bits, e.g.
uint64_t s = 1 << 32as surmised by @drhirsch, you don’t actually shift a 64-bit value but a 32-bit one. That is undefined behaviour.The most common results are a shift by
shift_distance % 32or 0, depending on what the hardware does (and assuming the compiler’s compile-time evaluation emulates the hardware semantics, instead of nasal demons.)Use
1ULL < 63to make the shift operandunsigned long longbefore the shift.