【发布时间】:2018-01-25 07:11:22
【问题描述】:
【问题讨论】:
标签: python
【问题讨论】:
标签: python
根据@nneonneo 的回答,这里有一个模拟 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]
【讨论】:
s = '{:0{}x}'.format(n, length*2).decode('hex')代替len(h)和zfill
为了回答您最初的问题,int 对象的 to_bytes 方法没有从 Python 3 反向移植到 Python 2.7。它被考虑但最终被拒绝。见讨论here。
【讨论】:
要在 Python 2.x 中打包任意长度的 longs,可以使用以下命令:
>>> n = 123456789012345678901234567890L
>>> h = '%x' % n
>>> s = ('0'*(len(h) % 2) + h).decode('hex')
>>> s
'\x01\x8e\xe9\x0f\xf6\xc3s\xe0\xeeN?\n\xd2'
这会以大端顺序输出数字;对于小端,反转字符串 (s[::-1])。
【讨论】:
您或许可以改用struct.pack:
>>> import struct
>>> struct.pack('>i', 123)
'\x00\x00\x00{'
它不会像int.to_bytes 那样做任意长度,但我怀疑你需要那个。
【讨论】: