logo

UTK Notes


Bitwise Operators

Topics

Operators

  • CPUs only allow us to manipulates BYTES, not BITS
  • Cannot directly manipulate bits
  • How do we manipulate bits?
    • Bitwise operators
      • Means “at-the-bit-level”

Logical AND & operator

  • Logical AND is a binary operator. Is signed agnostic.
  • Algorithm: line up bits. Where the column has two 1s, the result is 1. Otherwise, it is 0.
1
2
3
4
  0b0110_0110
& 0b0100_0100
-------------
  0b0100_0100

Logical OR | operator

  • Logical OR is a binary operator. Is signed agnostic.
  • Algorithm: line up bits. Where a column has at least a 1, the result is 1. Otherwise, it is 0.
1
2
3
4
  0b0110_0110
| 0b0100_0101
-------------
  0b0110_0111

Logical NOT ~ operator

  • Logical NOT is a unary operator. Is signed agnostic. Also called “one’s complement”
  • Algorithm: flip all 0s to 1s and all 1s to 0s.
1
~0b0110_0110 = 0b1001_1001

Logical XOR ^ operator

  • Logical XOR (exclusive OR) is a binary operator. Is signed agnostic.
  • Algorithm: line up bits. Where the column has exactly one 1, the result is 1. Otherwise, it is 0.
1
2
3
4
  0b0110_0110
^ 0b0100_0101
-------------
  0b0010_0011

Logical LSHIFT << operator

  • Logical LSHIFT (left shift) is a binary operator. Is signed agnostic.
  • value « number_of_shifts
    • Bits that fall off the left are discarded
    • 0s are added from the right
    • Mathematically: value * 2number_of_shifts
1
0b0100_1001 << 2 = 0b0010_0100

Logical RSHIFT >> operator

  • Logical RSHIFT (right shift) is a binary operator. Is signed agnostic.
  • unsigned_value » number_of_shifts
    • Bits that fall off the right are discarded
    • 0s are added from the left
    • Mathematically: unsigned_value / 2number_of_shifts
1
0b0100_1001 >> 2 = 0b0001_0010

Using Bitwise Operators

Quick Multiplication / Division

Left

  • a « 1 is the same as a * 2
  • a « 2 is the same as a * 4
  • a « 3 is the same as a * 8

Right

  • a » 1 is the same as a / 2
  • a » 2 is the same as a / 4
  • a » 3 is the same as a / 8

Test, Set, Clear

  • Test – Check to see if a single bit is 0 or 1
  • Set – Set a single bit to 1
  • Clear – Clear a single bit to 0

XOR Invertibility

  • XOR is an inversion of itself. Used in cryptography for “stream ciphers”.

Powerpoint