Bitwise Operators

Bitwise operators perform operations directly on the binary representation of numbers.

They are used in:

How Bitwise Operators work

Computers store numbers in binary (base-2), where each bit represents a power of two.

DecimalBinary
00000
10001
20010
30011
40100
50101
60110
70111
81000
91001
101010

Bitwise operations manipulate these individual bits.

Types of Bitwise Operators

AND (&)

Each bit is set to 1 only if both input bits are 1.

  1001  (9)
& 0011  (3)
------
  0001  (1)

OR (|)

Each bit is set to 1 if at least one input bit is 1.

  1001   (9)
| 0011   (3)
------
  1011  (11)

XOR (^)

Each bit is set to 1 only if the input bits are different.

  1001   (9)
^ 0011   (3)
------
  1010  (10)

NOT (~)

Inverts each bit.

~ 1001    (9)
------
  0110  (-10)

Note: Because of two’s complement representation, inverting all bits causes the number to become negative, and the formula becomes ~n equals -(n + 1)

Left Shift (<<)

Shifts bits left, multiplying by 2^n.

  0011  (3)
<<   1  // Shifting left by 1 bit (multiplying by 2)
------
  0110  (6)

Right Shift (>>)

Shifts bits right, dividing by 2^n, while preserving the sign.

  0011  (3)
>>   1  // Shifting right by 1 bit (dividing by 2)
------
  0001  (1)

Zero-Fill Right Shift (>>>)

Shifts bits right like >>, but always fills with zeros instead of preserving the sign bit.

Practical Applications

Checking if a number is even or odd

function isOdd(number) {
  return (number & 1) == 1;
}

If the last bit is 1, the number is odd.

Swapping two numbers without a temp variable

let a = 5;
let b = 3;
a = a ^ b;
b = a ^ b;
a = a ^ b;

No extra memory needed.

Using bitmasks for flags

We can set each bit to represent a permission.

const READ = 0b001;
const WRITE = 0b010;
const EXEC = 0b100;

const userPermissions = READ | WRITE; // 011

To check if the user has WRITE permission:

if (userPermissions & WRITE) {
  // has write access
}

Fast multiplication and division by powers of 2

n << 2; // Multiplies by 4
n >> 3; // Divides by 8

Find this post helpful? Subscribe and get notified when I post something new!