Ruby Bitwise Operators

There are 10 kinds of people: those who know binary and those who don’t.

For some algorithms, manipulating individual bits can save time. For these, an understanding of binary code and its comparison operations is useful, even in Ruby. The binary numeral system has only two numerals, 0 and 1. Each digit of a number represented in binary is referred to as a “bit”. These are the operations that Ruby provides to manipulate bits.

| (OR)

The `|` is the binary OR operator. When two numbers are compared with `|`, bits that are set to 1 in either number will be set to 1 in the result.

3 | 5 # => 7
#   011
# | 101
# 111

& (AND)

The `&` is the binary AND operator. When two numbers are compared in this way, all bits that are set in both of them will be set in the result.

3 & 5 # => 1
#   011
# & 101
# 001

^ (XOR)

The `^` is the binary XOR (Exclusive OR) operator. When two numbers are compared in this way, only bits that are set in one of them will be set in the result.

3 ^ 5 # => 6
#   011
# ^ 101
# 110

<< (left shift)

The `<<` will shift the bits of a number by the given number of spaces to the left, filling added bit positions with 0. This is comparable to multiplying the number by 2 the specified number of times.

5 << 2 # => 20
# 00101 << 10
# 10100

>> (right shift)

The `>>` will shift the bits of a number by the given number of spaces to the right, removing those that are shifted past the right-most bit position. This is comparable to dividing the number by 2 the specified number of times.

7 >> 2 # => 1
# 111 >> 10
# 001

Applications

Counting the number of set bits in a positive integer is quite easy with bitwise operators.

def bit_count(number)
count = 0
while number > 0
count += number & 1 # add one if the ones bit is set
number >>= 1 # shifts and resets the number
end
count
end

A positive power of two can be identified in one step:

def power_of_two?(number)
number & number - 1 == 0
end

And it is possible to determine if a number is odd (not recommended, though):

def odd?(number)
number & 1 == 1
end

Consider also having a look at the complement operator (~), which flips all of the bits in a number!