-
-
Save oshinko/e436af956b01421b0d904e814d0b81d6 to your computer and use it in GitHub Desktop.
Python version of unsigned integer 7-bit encoder and decoder
This file contains 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
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 bytes(data) | |
def decode_from_7bit(data): | |
""" | |
Decode 7-bit encoded int from str data | |
""" | |
result = 0 | |
for index, byte in enumerate(data): | |
result |= (byte & 0x7f) << (7 * index) | |
if byte & 0x80 == 0: | |
break | |
return result | |
def test(): | |
""" | |
Test encoding and decoding | |
""" | |
value = 0 | |
res = encode_to_7bit(value) | |
assert res == b'\x00', 'Invalid encoding of %s' % value | |
value = 127 | |
res = encode_to_7bit(value) | |
assert res == b'\x7f', 'Invalid encoding of %s' % value | |
value = 256 | |
res = encode_to_7bit(value) | |
assert res == b'\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