Skip to main content

Bit Magic

  • negative numbers are represented in 2's complement in most languages
  • Range: [-2 n-1 to 2 n-1 - 1]; n - number of bits
  • Range for unsigned: [0,2n1][0 , 2^n - 1]
  • 2's complement - 1. invert all bits; 2. add 1
info

leading bit is 1 for negative numbers

Bitwise Operators

  • Bitwise AND: &
  • Bitwise OR: |
  • Bitwise XOR : ^
AB&|^
00000
01011
10011
11110
  • Bitwise Not: ~
x = 5 # 0...0101
print(~x) # -6 # 1...1010

Shift Operators

  • Left Shift: <<
  • Right Shift: >>
x=5 # 101
x << 2 # 10100
x >> 3 # 000

x << n # x * 2^n
1 << n # 2^n