Skip to content

Instantly share code, notes, and snippets.

@vishaltelangre
Last active August 31, 2018 18:01
Show Gist options
  • Save vishaltelangre/8b2a273aed66e4b61fb3e9d5e0272e08 to your computer and use it in GitHub Desktop.
Save vishaltelangre/8b2a273aed66e4b61fb3e9d5e0272e08 to your computer and use it in GitHub Desktop.
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment