我有一个非负的int,我想有效地将它转换为包含相同数据的big-endian字符串.例如,int 1245427(0x1300F3)应该生成一个长度为3的字符串,其中包含三个字符,其字节值为0x13,0x00和0xf3.
我的整数是35(基数为10)的数字.
我该怎么做呢?
Aym*_*ieh 43
您可以使用struct模块:
import struct
print struct.pack('>I', your_int)
Run Code Online (Sandbox Code Playgroud)
'>I'是格式字符串.>表示大端,I表示unsigned int.查看文档以获取更多格式字符.
Jan*_*sen 40
在Python 3.2+中,您可以使用int.to_bytes:
>>> n = 1245427
>>> n.to_bytes((n.bit_length() + 7) // 8, 'big') or b'\0'
b'\x13\x00\xf3'
Run Code Online (Sandbox Code Playgroud)
>>> (1245427).to_bytes(3, byteorder='big')
b'\x13\x00\xf3'
Run Code Online (Sandbox Code Playgroud)
pts*_*pts 13
这很快,适用于小型和(任意)大型整数:
def Dump(n):
s = '%x' % n
if len(s) & 1:
s = '0' + s
return s.decode('hex')
print repr(Dump(1245427)) #: '\x13\x00\xf3'
Run Code Online (Sandbox Code Playgroud)
可能最好的方法是通过内置的struct模块:
>>> import struct
>>> x = 1245427
>>> struct.pack('>BH', x >> 16, x & 0xFFFF)
'\x13\x00\xf3'
>>> struct.pack('>L', x)[1:] # could do it this way too
'\x13\x00\xf3'
Run Code Online (Sandbox Code Playgroud)
或者 - 我通常不推荐这个,因为它容易出错 - 你可以通过移动和chr()功能"手动"完成它:
>>> x = 1245427
>>> chr((x >> 16) & 0xFF) + chr((x >> 8) & 0xFF) + chr(x & 0xFF)
'\x13\x00\xf3'
Run Code Online (Sandbox Code Playgroud)
出于好奇,为什么你只想要三个字节?通常你将这样一个整数打包成一个完整的32位(一个C unsigned long),并使用struct.pack('>L', 1245427)但跳过这[1:]一步?
基于@pts答案的单源Python 2/3兼容版本:
#!/usr/bin/env python
import binascii
def int2bytes(i):
hex_string = '%x' % i
n = len(hex_string)
return binascii.unhexlify(hex_string.zfill(n + (n & 1)))
print(int2bytes(1245427))
# -> b'\x13\x00\xf3'
Run Code Online (Sandbox Code Playgroud)
def tost(i):
result = []
while i:
result.append(chr(i&0xFF))
i >>= 8
result.reverse()
return ''.join(result)
Run Code Online (Sandbox Code Playgroud)