Last active
September 22, 2016 14:31
-
-
Save yyogo/a3ec66110447a8e3a3d4f0c04f723a12 to your computer and use it in GitHub Desktop.
Convert longs to / from bytes, mimicking behavior of Python 3.6 int.from/to_bytes
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
def bytes2int(data, byteorder='little', signed=False): | |
""" replicate int.from_bytes from python3 """ | |
if byteorder == 'little': | |
data = reversed(data) | |
elif byteorder != 'big': | |
raise ValueError("byteorder must be either 'little' or 'big'") | |
bl = bytearray(data) | |
val = 0L | |
for b in bl: | |
val <<= 8 | |
val += b | |
if signed: | |
bl = (val.bit_length() + 7) // 8 * 8 | |
if val & (1 << (bl - 1)): | |
return -((1 << bl) - val) | |
return val | |
def int2bytes(n, byteorder='little', size=None, signed=False): | |
""" replicate int.to_bytes from python3 """ | |
if byteorder not in ('little', 'big'): | |
raise ValueError("byteorder must be either 'little' or 'big'") | |
bl = n.bit_length() | |
if not signed and n < 0: | |
raise OverflowError("can't convert negative int to unsigned") | |
if signed: | |
bl += 1 | |
rsize = (bl + 7) // 8 | |
if signed and n < 0: | |
n = (1 << (rsize * 8)) + n | |
if size is None: | |
size = rsize | |
elif size < rsize: | |
raise OverflowError("int too big to convert") | |
buf = bytearray(size) | |
if byteorder == 'big': | |
it = xrange(size - 1, -1, -1) | |
else: | |
it = xrange(size) | |
for i in it: | |
buf[i] = n & 0xff | |
n >>= 8 | |
return bytes(buf) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment