I am trying to achieve logical right shift in Arduino(i.e. avoid sign extension), and after reading the Arduino BitShift guide (https://www.arduino.cc/en/Reference/Bitshift), it suggests that shifting unsigned variables to the right, wont cause sign extension:
When you shift x right by y bits (x >> y), and the highest bit in x is a 1, the behavior depends on the exact data type of x. If x is of type int, the highest bit is the sign bit, determining whether x is negative or not, as we have discussed above. In that case, the sign bit is copied into lower bits, for esoteric historical reasons:
int x = -16; // binary: 1111111111110000 int y = x >> 3; // binary: 1111111111111110 This behavior, called sign extension, is often not the behavior you want. Instead, you may
wish zeros to be shifted in from the left. It turns out that the right shift rules are different for unsigned int expressions, so you can use a typecast to suppress ones being copied from the left.
In my tests, it doesn't work like that:
Serial.print( ((uint32_t)(1<<15)) >> 15, BIN);
Prints:
11111111111111111
Which means, there's sign extension going on. I've also tried the suggested example from there, with the same results.
Am I doing something wrong? Also Is it possible to do a shift and force the operation to be logical instead of arithmetic?
(1u << 15) >> 15
. – Some programmer dude>>
over negative values is implementation-defined behavior. – Asu