Skip to content

Instantly share code, notes, and snippets.

@delimitry
Last active November 7, 2022 16:09
Show Gist options
  • Save delimitry/7c56945c428ec78ebf2a to your computer and use it in GitHub Desktop.
Save delimitry/7c56945c428ec78ebf2a to your computer and use it in GitHub Desktop.
Python version of unsigned integer 7-bit encoder and decoder
#!/usr/bin/evn python
# -*- coding: utf8 -*-
def encode_to_7bit(value):
"""
Encode unsigned int to 7-bit str data
"""
data = []
number = abs(value)
while number >= 0x80:
data.append((number | 0x80) & 0xff)
number >>= 7
data.append(number & 0xff)
return ''.join(chr(char) for char in data)
def decode_from_7bit(data):
"""
Decode 7-bit encoded int from str data
"""
result = 0
for index, char in enumerate(data):
byte_value = ord(char)
result |= (byte_value & 0x7f) << (7 * index)
if byte_value & 0x80 == 0:
break
return result
def test():
"""
Test encoding and decoding
"""
value = 0
res = encode_to_7bit(value)
assert res == '\x00', 'Invalid encoding of %s' % value
value = 127
res = encode_to_7bit(value)
assert res == '\x7f', 'Invalid encoding of %s' % value
value = 256
res = encode_to_7bit(value)
assert res == '\x80\x02', 'Invalid encoding of %s' % value
value = 0
res = encode_to_7bit(value)
assert decode_from_7bit(encode_to_7bit(value)) == value, 'Invalid decoding of %s' % value
value = 42
res = encode_to_7bit(value)
assert decode_from_7bit(encode_to_7bit(value)) == value, 'Invalid decoding of %s' % value
value = 1082376495
res = encode_to_7bit(value)
assert decode_from_7bit(encode_to_7bit(value)) == value, 'Invalid decoding of %s' % value
if __name__ == '__main__':
try:
test()
print('OK')
except Exception as ex:
print('FAILED: %s' % ex)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment