Bitwise Operations: AND, OR, XOR, NOT

Master bitwise AND, OR, XOR, and NOT operations with truth tables and practical examples. Learn applications in flags, masks, permissions, and bit manipulation.

Binary OperandsBinary ResultArithmetic

Detailed Explanation

Bitwise operations work on individual bits of binary numbers. They are fundamental to low-level programming, cryptography, graphics, and performance optimization.

The four basic bitwise operations:

AND (&) — Both bits must be 1:

  1010 & 1100 = 1000

Use case: Masking specific bits. To extract the lower 4 bits of a byte, AND with 0x0F.

OR (|) — At least one bit must be 1:

  1010 | 1100 = 1110

Use case: Setting flags. To enable bit 3, OR with 0x08.

XOR (^) — Exactly one bit must be 1:

  1010 ^ 1100 = 0110

Use case: Toggling bits, simple encryption, swapping values without a temporary variable.

NOT (~) — Inverts every bit:

  ~1010 = 0101

Use case: Creating inverse masks, two's complement negation.

Practical applications:

  • Feature flags: Combine permissions using OR: READ | WRITE = 0b110. Check with AND: flags & READ !== 0.
  • IP subnetting: AND an IP with a subnet mask to get the network address.
  • Color manipulation: Extract the green channel from #4169E1: (0x4169E1 >> 8) & 0xFF = 0x69 = 105.
  • Hash functions: XOR is used extensively in hash algorithms because it distributes bits evenly.
  • Cryptography: XOR is the foundation of stream ciphers and one-time pads: plaintext ^ key = ciphertext, and ciphertext ^ key = plaintext.

Common bit tricks:

  • Check if a number is even: n & 1 === 0
  • Check if a number is a power of 2: n & (n - 1) === 0
  • Clear the lowest set bit: n & (n - 1)
  • Isolate the lowest set bit: n & (-n)

Mastering bitwise operations makes you more effective at systems programming, competitive coding, and understanding how hardware processes data.

Use Case

Systems programmers use bitwise AND operations to apply bitmask flags when configuring hardware registers, checking file permissions, or filtering network packet headers.

Try It — Number Base Converter

Open full tool