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.
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
# | 101
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
# & 101
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
# ^ 101
<< (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
>> (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
Counting the number of set bits in a positive integer is quite easy with bitwise operators.
count = 0
while number > 0
count += number & 1 # add one if the ones bit is set
number >>= 1 # shifts and resets the number
A positive power of two can be identified in one step:
number & number - 1 == 0
And it is possible to determine if a number is odd (not recommended, though):
number & 1 == 1
Consider also having a look at the complement operator (~), which flips all of the bits in a number!