Skip to content

Instantly share code, notes, and snippets.

@blakejakopovic
Created November 29, 2022 17:05
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 blakejakopovic/8b838842353db08772be112f6945638d to your computer and use it in GitHub Desktop.
Save blakejakopovic/8b838842353db08772be112f6945638d to your computer and use it in GitHub Desktop.
Calculate leading zero bits for string
#!/usr/bin/env ruby
def hex_to_bytes(s)
s.scan(/.{1,2}/).map{|b| b.to_i(16)}
end
def zero_bits(b)
n = 0
if b == 0
return 8
end
while true do
b >>= 1
if b != 0
n += 1
else
break
end
end
return 7 - n;
end
def count_leading_zero_bits(hash)
total = 0
for i in 0...32 do
bits = zero_bits(hash[i]);
total += bits;
break if (bits != 8)
end
return total
end
# x = hex_to_bytes('000000000e9d97a1ab09fc381030b346cdd7a142ad57e6df0b46dc9bef6c7e2d')
# puts count_leading_zero_bits(x) # => 36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment