Has Python 3 to_bytes been back-ported to python 2.7?

Posted on

Question :

Has Python 3 to_bytes been back-ported to python 2.7?

This is the function I’m after: –

http://docs.python.org/3/library/stdtypes.html#int.to_bytes

I need big endianness support.

Asked By: Jason

||

Answer #1:

Based on the answer from @nneonneo, here is a function that emulates the to_bytes API:

def to_bytes(n, length, endianess='big'):
    h = '%x' % n
    s = ('0'*(len(h) % 2) + h).zfill(length*2).decode('hex')
    return s if endianess == 'big' else s[::-1]
Answered By: miracle2k

Answer #2:

To answer your original question, the to_bytes method for int objects was not back ported to Python 2.7 from Python 3. It was considered but ultimately rejected. See the discussion here.

Answered By: Ned Deily

Answer #3:

To pack arbitrary-length longs in Python 2.x, you can use the following:

>>> n = 123456789012345678901234567890L
>>> h = '%x' % n
>>> s = ('0'*(len(h) % 2) + h).decode('hex')
>>> s
'x01x8exe9x0fxf6xc3sxe0xeeN?nxd2'

This outputs the number in big-endian order; for little endian, reverse the string (s[::-1]).

Answered By: nneonneo

Answer #4:

You can probably use struct.pack instead:

>>> import struct
>>> struct.pack('>i', 123)
'x00x00x00{'

It doesn’t do arbitrary lengths in the way int.to_bytes does, but I doubt you need that.

Answered By: Cairnarvon

Leave a Reply

Your email address will not be published. Required fields are marked *