Is Python 3 to_bytes enabled in python 2.7?

This is the function that I use: -

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

I need a lot of support support.

+6
source share
4 answers

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] 
+13
source

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

+11
source

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

 >>> n = 123456789012345678901234567890L >>> h = '%x' % n >>> s = ('0'*(len(h) % 2) + h).decode('hex') >>> s '\x01\x8e\xe9\x0f\xf6\xc3s\xe0\xeeN?\n\xd2' 

This prints the number in big-endian order; for the small end, change the line ( s[::-1] ).

+7
source

You can use struct.pack :

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

It does not execute arbitrary lengths in the int.to_bytes method, but I doubt you need it.

+2
source

All Articles