Last active
December 21, 2015 09:59
-
-
Save aasmith/6289121 to your computer and use it in GitHub Desktop.
HPACK Integer [de]compression
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
# encode int i onto n bits | |
def encode(i, n) | |
a = [] | |
i = i.to_i | |
# Max number that can be stored on initial bits | |
max = 2**n - 1 | |
if i < max | |
a << i | |
else | |
a << max | |
i -= max | |
while i >= 128 | |
a << (i % 128 + 128) | |
i /= 128 | |
end | |
a << i | |
end | |
a | |
end | |
p encode(1337,5) | |
# decode bytes into int, using last n bits of first byte | |
def decode(bytes, n) | |
bytes = bytes.to_enum | |
# How much can be stored in n bits | |
max = 2**n-1 | |
i = bytes.next & max | |
# if all bits are set, then there are more bytes to extract. | |
if i == max | |
shift = 0 | |
begin | |
b = bytes.next | |
# read 7 LSB | |
i += (b & 127) << shift | |
shift += 7 | |
end until b & 128 == 0 # until MSB is no longer set | |
end | |
i | |
end | |
p decode(encode(1337, 5), 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Saved two bytes! 😄