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

Eric Eisner ede at mit.edu
Mon Aug 10 13:02:08 CEST 2009

On Mon, Aug 10, 2009 at 19:30, Nick Coghlan<ncoghlan at gmail.com> wrote:
> Mark Dickinson wrote:
>> 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:
> bytes.from_int
> bytearray.from_int
> int.from_bytes
> 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.

For completeness, any function converting from int to bytes needs to
accept the arguments size, endianness, and two's complement handling.
By default, size and two's complement could be inferred from the int's

Any function converting from bytes to int needs to accept the
arguments endianness and two's complement. The function cannot really
make a reasonable assumption about either.

Having this much to specify in bytes.from_int or bytes.to_int seems a
little overwhelming (to me anyway). It is already more complicated
than the analogous bytes.decode for strings.

What about a putting this in module support, and putting each of these
options in its own named method? Some dummy examples that may need
better names:
base256.encode_le(0x123456, size=5) # returns b'\x56\x34\x12\x00\x00'
base256.decode_le_positive(b'\xff\xce') # returns 0xceff


More information about the Python-ideas mailing list