Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
55 lines (44 sloc) 1.28 KB
# -*- coding: utf-8 -*-
# Copyright © 2011 Andrew D. Yates
# All Rights Reserved
"""Bytes to Integer Functions.
`int` types may be cast as `long`
__authors__ = ['"Andrew D. Yates" <>']
def bytes_to_int(s):
"""Return converted bytestring to integer.
s: str of bytes
int: numeric interpretation of binary string `s`
# int type casts may return a long type
return int(s.encode('hex'), 16)
def int_to_bytes(num):
"""Return converted integer to bytestring.
Note: string encoding is faster than divmod(num, 256) in Python.
num: integer, non-negative
str: bytestring of binary data to represent `num`
ValueError: `num` is not a non-negative integer
if not is_natural(num, include_zero=True):
raise ValueError("%s is not a non-negative integer.")
hexed = "%x" % num
# align hexadecimal string to byte boundaries
if len(hexed) % 2 == 1:
hexed = '0%s' % hexed
return hexed.decode('hex')
def is_natural(value, include_zero=False):
"""Return if value is a natural integer in Python.
bool: is value a natural number?
return all((
isinstance(value, (int, long)),
value >= 0,
not (value == 0 and not include_zero),