Skip to content

Instantly share code, notes, and snippets.

@muyesh
Created October 7, 2018 22:59
Show Gist options
  • Save muyesh/8fcb2c1461ca030a40b91a0dd6ed5ee9 to your computer and use it in GitHub Desktop.
Save muyesh/8fcb2c1461ca030a40b91a0dd6ed5ee9 to your computer and use it in GitHub Desktop.
Simple ULEB128 by Ruby
#!/usr/bin/env ruby
# Unsigned LEB128 Converter
# https://en.wikipedia.org/wiki/LEB128
def leb128_encode( n )
tmp = []
while true do
tmp.push( ((n & 0x7F) | 0x80 ).chr )
if n <= 0x7F
tmp.push( (tmp.pop.ord ^ 0x80).chr )
break
end
n = (n >> 7)
end
puts tmp[0].bth
tmp.join
end
def leb128_decode( bytes , offset = 0)
bytes = bytes[offset..-1]
n = 0
cnt = 0
bytes.each_byte {|b|
n = n | ( ( b.ord & 0x7F ) << (7 * cnt) )
cnt += 1
if b.ord & 0x80 == 0
return n, offset + cnt
end
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment