Created
November 29, 2022 17:05
-
-
Save blakejakopovic/8b838842353db08772be112f6945638d to your computer and use it in GitHub Desktop.
Calculate leading zero bits for string
This file contains 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
#!/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