Tuesday, August 4, 2015

Unsigned integer 7-bit encoder and decoder in Python

#!/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)
view raw uint_7bit.py hosted with ❤ by GitHub