[Python-ideas] Direct byte<->int conversions (was Re: bitwise operations on bytes)

Nick Coghlan ncoghlan at gmail.com
Mon Aug 10 12:30:38 CEST 2009

Mark Dickinson wrote:
> On Sat, Aug 8, 2009 at 10:31 PM, Guido van Rossum<guido at python.org> wrote:
>> [...] I'd be okay with a standard API to transform a
>> byte array into an integer and vice versa -- there you can be explicit
>> about byte order and what to do about negative numbers. [...]
> That would also be a welcome addition.  It's been requested on
> bugs.python.org at least a couple of times[1][2], and the C code
> to do the conversions already exists (_PyLong_{As,From}_ByteArray
> in longobject.c), so it wouldn't be too much work to implement.
> The main problem would be deciding exactly what the API should be
> and where to put it.

My suggestion would be to provide the relevant constructors as class
methods on int, bytes and bytearray:


Alternatively, the int.from_bytes classmethod could be replaced with a
"to_int" instance method on bytes and bytearray.

The method signatures would need to closely resemble the C API. In
particular, for the conversion from int to bytes being able to state a
desired size would both allow detection of cases where the value is too
large as well as proper padding of the two's complement sign bit.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list