Created
October 7, 2018 23:20
-
-
Save muyesh/5cceb6a8f8d857e9c5bd81fc0bce0760 to your computer and use it in GitHub Desktop.
Bitcoin Core Base128 Serializer by Ruby
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
#!/usr/bin/env ruby | |
# Bitcoin Core Base128 Serializer | |
# https://github.com/bitcoin/bitcoin/blob/v0.16.3/src/serialize.h#L317 | |
def b128_encode( n ) | |
puts (n).to_s(2) | |
tmp = [] | |
while true do | |
tmp.push( ((n & 0x7F) | (tmp.length>0 ? 0x80 : 0x00) ).chr ) | |
if n <= 0x7F | |
break | |
end | |
n = (n >> 7) - 1 | |
end | |
tmp.reverse.join | |
end | |
def b128_decode( bytes , offset = 0) | |
bytes = bytes[offset..-1] | |
n = 0 | |
bytes.each_byte {|b| | |
offset += 1 | |
n = ( n << 7 ) | ( b.ord & 0x7F ) | |
if b.ord & 0x80 == 128 | |
n += 1 | |
else | |
return n, offset | |
end | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment