Skip to content

Instantly share code, notes, and snippets.

@aasmith
Last active December 21, 2015 09:59
Show Gist options
  • Save aasmith/6289121 to your computer and use it in GitHub Desktop.
Save aasmith/6289121 to your computer and use it in GitHub Desktop.
HPACK Integer [de]compression
# 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)
@rantler
Copy link

rantler commented Aug 22, 2013

Saved two bytes! 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment