Skip to content

Instantly share code, notes, and snippets.

@coder36
Created June 18, 2014 18:21
Show Gist options
  • Select an option

  • Save coder36/220e7ba6c9c326988d3c to your computer and use it in GitHub Desktop.

Select an option

Save coder36/220e7ba6c9c326988d3c to your computer and use it in GitHub Desktop.
Bit counter algorithm

Counts the number of bits in an array. Assumes array of 8 bit values

def count_bits a
  a.inject(0) do |total, n| 
    (0...8).each do |j|
      total = total + ( (n>>j) & 0x01 )
    end
    total
  end
end


2.1.1 :041 > count_bits [1,1,255,255]
 => 18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment