LEB128
This gem is a pair of utility functions for encoding and decoding LEB128-compressed integers.
As a visual example, this is an excerpt from the LEB128 Wikipedia page describing how an integer is encoded into an unsigned LEB128:
10011000011101100101 In raw binary
010011000011101100101 Padded to a multiple of 7 bits
0100110 0001110 1100101 Split into 7-bit groups
00100110 10001110 11100101 Add high 1 bits on all but last group to form bytes
0x26 0x8E 0xE5 In hexadecimal
0xE5 0x8E 0x26 Output stream
Installation
Add this line to your application's Gemfile:
gem 'leb128'
And then execute:
$ bundle
Or install it yourself as:
$ gem install leb128
Usage
Require the Gem:
require 'leb128'
Encoding and Decoding
Encode integers into LEB128-compressed data by using the encode
method. The first argument takes an integer, and the second takes a bool that tells whether to use a signed datatype or not. The following encodes the given integer and returns a new StringIO containing it:
LEB128.encode(-0x143f, true)
#=> #<StringIO:0x00000003533e20>
Decode LEB128-compressed data into integers by using the decode
method. The first argument takes a StringIO, the second takes a bool that tells whether to use a signed datatype or not, and the third takes an integer that sets the position of the StringIO (default is 0). The following decodes the given StringIO and returns a new integer containing it:
sio = StringIO.new
sio.putc(0xc1)
sio.putc(0x57)
LEB128.decode(sio, false)
#=> 11201
License
This gem is available as open source under the terms of the MIT License. See LICENSE.md and https://opensource.org/licenses/MIT.