Bit manipulation

suggest change

In Ruby, all integers belong to the Integer class and support arbitrary precision (handling values of unlimited size without arithmetic overflow). Ruby treats integers as two's complement binary representations and provides native bitwise operators, direct bit indexing, and bitfield support.

Bitwise Operators

Ruby supports standard bitwise operators:

a = 0b1100 # 12 in decimal
b = 0b1010 # 10 in decimal

# Bitwise AND (&)
puts (a & b).to_s(2) #=> "1000" (8)

# Bitwise OR (|)
puts (a | b).to_s(2) #=> "1110" (14)

# Bitwise XOR (^)
puts (a ^ b).to_s(2) #=> "110"  (6)

# Bitwise NOT (~) - two's complement negation (~x = -x - 1)
puts ~a #=> -13

# Left shift (<<) - multiplies by 2^n
puts (a << 2) #=> 48 (12 * 4)

# Right shift (>>) - integer division by 2^n
puts (a >> 1) #=> 6 (12 / 2)

Indexing Individual Bits with Integer#[]

A distinctive feature of Ruby is that Integer implements the bracket operator ([]) to read single bits or bit slices directly:

n = 42 # Binary: 0b101010

# Accessing single bits (0-indexed from least significant bit)
puts n[0] #=> 0 (LSB)
puts n[1] #=> 1
puts n[2] #=> 0
puts n[3] #=> 1
puts n[5] #=> 1 (MSB)

# Slicing bit ranges: n[start, length]
puts n[1, 3].to_s(2) #=> "101" (extracts 3 bits starting at bit 1: bits 1, 2, 3)

# Slicing with Range: n[start..end]
puts n[0..2].to_s(2) #=> "10"  (bits 0, 1, 2 = 0b010)

Common Bitwise Recipes

Setting, Clearing, and Toggling Bits

# Set bit k (0-indexed)
def set_bit(value, bit)
  value | (1 << bit)
end

# Clear bit k
def clear_bit(value, bit)
  value & ~(1 << bit)
end

# Toggle (flip) bit k
def toggle_bit(value, bit)
  value ^ (1 << bit)
end

# Test if bit k is set
def bit_set?(value, bit)
  value[bit] == 1
  # or: (value & (1 << bit)) != 0
end

num = 0b1000 # 8
num = set_bit(num, 0)    # 0b1001 (9)
num = toggle_bit(num, 3) # 0b0001 (1)
num = clear_bit(num, 0)  # 0b0000 (0)

Checking for Powers of Two

A positive number is a power of two if and only if (n & (n - 1)) == 0:

def power_of_two?(n)
  n > 0 && (n & (n - 1)).zero?
end

puts power_of_two?(16) #=> true
puts power_of_two?(18) #=> false

Counting Set Bits (Popcount)

To count the number of 1s in a positive integer:

def popcount(n)
  n.digits(2).count(1)
end

puts popcount(0b110101) #=> 4

Bit Flags and Permission Masks

Bit manipulation is ideal for modeling compact combinations of boolean attributes or permissions:

module Permissions
  NONE    = 0
  READ    = 1 << 0 # 1
  WRITE   = 1 << 1 # 2
  EXECUTE = 1 << 2 # 4
  DELETE  = 1 << 3 # 8
end

# Grant READ and WRITE permissions
user_perm = Permissions::READ | Permissions::WRITE

# Check if user has WRITE permission
can_write = (user_perm & Permissions::WRITE) != 0 # true

# Revoke WRITE permission
user_perm &= ~Permissions::WRITE

# Check permissions again
can_write = (user_perm & Permissions::WRITE) != 0 # false
can_read  = (user_perm & Permissions::READ) != 0  # true

Binary Data Conversion with pack and unpack

When interfacing with binary protocols or network packets:

# Pack an array of integers into an 8-bit unsigned byte stream
binary_data = [0x41, 0x42, 0x43].pack('C*') # "ABC"

# Unpack bytes into binary representation string
bits = binary_data.unpack1('B*')
puts bits #=> "010000010100001001000011"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents