What bitwise operations are for

Bitwise operations work on each binary digit separately. AND keeps 1 only where both numbers have 1, OR where at least one does, XOR where they differ, NOT flips them all. They are a processor's most basic instructions, and the fastest.

They are used to read and set single flags in an integer, to apply masks like network ones, for Unix file permissions, for colours packed into an integer, for checksums and cryptography. AND with 0x0F keeps the low four bits; OR with 0x80 sets the top one.

Shifting left by n places multiplies by 2^n, shifting right divides. With negative numbers the difference between a logical shift, which feeds in zeros, and an arithmetic one, which copies the sign bit, matters: -16 >> 2 is -4, while the logical shift gives a large positive number.

Common mistakes

  • Forgetting the word width: NOT 0 is 255 in 8 bits but 4294967295 in 32.
  • Using a logical shift on a signed number and expecting a division: negatives need the arithmetic one.
  • In JavaScript, using & and | on numbers beyond 32 bits: they are silently truncated. 64 bits need BigInt.

Frequently asked questions

What is the difference between >> and >>>?

Both shift right. >> is arithmetic and copies the sign bit, so negative numbers stay negative; >>> is logical and feeds in zeros, treating the number as unsigned.

What is XOR for?

Swapping or comparing bits: A XOR B shows which bits differ, A XOR A is 0 and A XOR B XOR B gives back A. That is why it underlies checksums, parity and many ciphers.

How do I check whether a bit is set?

AND the number with a mask that has only that bit set: if the result is not zero, the bit is set. Bit k has the mask 1 << k.

How this calculation works

Each operation acts on the bits in the same position: AND = 1 if both are 1, OR = 1 if at least one is 1, XOR = 1 if they differ, NOT inverts. A << n = A · 2^n truncated to the width w; A >>> n = ⌊A / 2^n⌋ unsigned; A >> n divides keeping the sign. Rotating left by n is (A << n) OR (A >>> (w − n)). The signed value is the unsigned one minus 2^w when the top bit is 1.