Skip to content

Instantly share code, notes, and snippets.

@mleszcz
Created June 20, 2011 12:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mleszcz/1035523 to your computer and use it in GitHub Desktop.
Save mleszcz/1035523 to your computer and use it in GitHub Desktop.
count number of set bits in string representing hexadecimal number
def setbits_count(s)
# bits map
bm = {"0" => 0, "1" => 1, "2" => 1, "3" => 2, "4" => 1, "5" => 2, "6" => 2, "7" => 3,
"8" => 1, "9" => 2, "A" => 2, "B" => 3, "C" => 2, "D" => 3, "E" => 3, "F" => 4}
sum = 0
0.upto(s.size-1) { |i| sum += bm[s[i]] }
sum
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment