Skip to content

Instantly share code, notes, and snippets.

@muyesh
Created October 7, 2018 23: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 muyesh/5cceb6a8f8d857e9c5bd81fc0bce0760 to your computer and use it in GitHub Desktop.
Save muyesh/5cceb6a8f8d857e9c5bd81fc0bce0760 to your computer and use it in GitHub Desktop.
Bitcoin Core Base128 Serializer by Ruby
#!/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