Created
January 29, 2012 14:44
-
-
Save jamesu/1699113 to your computer and use it in GitHub Desktop.
Counting bits without testing every bit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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