Skip to content

Instantly share code, notes, and snippets.

@jamesu
Created January 29, 2012 14:44
Show Gist options
  • Save jamesu/1699113 to your computer and use it in GitHub Desktop.
Save jamesu/1699113 to your computer and use it in GitHub Desktop.
Counting bits without testing every bit
# Counts bits without testing every single bit, using a simple lookup table.
# Assumes a maximum size of 32bits.
$blookup = (0..255).map do |i|
count = 0
(0..7).each { |j| count += 1 if (i>>j) & 0x1 != 0 }
count
end
# Count
def countbits(number)
count = 0
num = number
count += $blookup[num & 0xFF]; num >>= 8
count += $blookup[num & 0xFF]; num >>= 8
count += $blookup[num & 0xFF]; num >>= 8
count += $blookup[num & 0xFF]; num >>= 8
count
end
puts "Bits set: #{countbits(ARGV[0].to_i)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment