Bitwise shifting by a negative number

Hi there,

A rapid test in Xcode shows that bitwise shifting by a negative number seems to reverse the direction of the shift.

I didn't find any confirmation of this behaviour (wich is undefined in C for example), even in the Advanced Operators chapter of the Swift doc.

Is that a robust and stable functionality? Can I use it without risk in my code.

Thanks!

I remember reading about this recently, but I cannot find the source. Than I remembered it is in the Swift standard lib documentation.

That is expected behavior. It should be as stable as shifting by a positive number in the opposite direction.

Quoting the Standard Library Documentation:

Using a negative value as `rhs` is the same as performing a right shift with `abs(rhs)`.

let a = x << -3
// a == 3                         // 0b00000011
let b = x >> 3
// b == 3                         // 0b00000011
1 Like

I didn't think to look there. Thank you so much Evan!
Now I can code with peace of mind :wink:.