Count number of bits in a Ruby integer

How would one count the number of set bits in an integer? If it was a C/C++ application I guess I would do a for-loop and shift out the bits and keep a running sum. I would be hard pressed to do it in less than three lines of code and would probably do it in five to include the curly braces.

Given the same problem and having to find a solution in Ruby I came up with this:

v.to_s(2).split(//).inject(0) { |s,i| s + i.to_i }

In other words; first convert the integer to a binary string and split the string into an array. Then use the inject method to start with zero (remember even numbers are objects in Ruby) and iterate over the array with a code block, adding each digit in the binary string to get the total sum.

One reply on “Count number of bits in a Ruby integer”

Comments are closed.