Instantly share code, notes, and snippets. vishaltelangre/left_shift_and_right_shift_operators.md Last active Aug 31, 2018

Left Shift (<<) and Right Shift (>>) Operators

Left Shift (<<) Operator

x << y == x * (2 ^ y)
Examples
1 << 5 == 1 * (2 ^ 5) == 32
1 << 3 == 1 * (2 ^ 3) == 8
1 << 8 == 1 * (2 ^ 8) == 256
2 << 8 == 2 * (2 ^ 8) == 512
5 << 3 == 5 * (2 ^ 3) == 40
10 << 2 == 10 * (2 ^ 2) == 40

Right Shift (>>) Operator

x >> y == x / (2 ^ y)
Examples
1 >> 1 == 1 / (2 ^ 1) == 0
2 >> 1 == 2 / (2 ^ 1) == 1
3 >> 1 == 3 / (2 ^ 1) == 1
4 >> 1 == 4 / (2 ^ 1) == 2
5 >> 1 == 5 / (2 ^ 1) == 2
6 >> 1 == 6 / (2 ^ 1) == 3
35 >> 1 == 35 / (2 ^ 1) == 17
35 >> 2 == 35 / (2 ^ 2) == 8
35 >> 3 == 35 / (2 ^ 3) == 4
35 >> 5 == 35 / (2 ^ 5) == 1
35 >> 8 == 35 / (2 ^ 8) == 0

Notes

• If the number is shifted more than the size of integer, the behaviour is undefined. For example, 1 << 33 is undefined if integers are stored using 32 bits.

• Also, the behavior is unexpected for negative numbers.

to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.