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

前端 未结 4 1295
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 12:07

This is the function I\'m after: -

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

I need big endianness support.

4条回答
  •  误落风尘
    2020-11-30 12:27

    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
    '\x01\x8e\xe9\x0f\xf6\xc3s\xe0\xeeN?\n\xd2'
    

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

提交回复
热议问题