我需要通过串行连接发送32位整数,如下所示:0xc6bf6f34
应该变为:b'\xc6\xbf\x6f\x34'
。
为此,我创建了这个,但是,在进行这样的编码之后,我想知道它是否可以通过标准库中的某些内容改进 pythonicism :
def ltonlba(value):
''' ltonlba : Long to Network Long Byte Array '''
from socket import htonl
value = htonl(value)
ba = b''
for i in range(4):
ba += chr((value) & 0xff)
value >>= 8
return ba
答案 0 :(得分:3)
如果您使用的是Python 3.2+,则可以使用int.to_bytes
:
>>> 0xc6bf6f34.to_bytes(4, 'little') # 4 bytes = 32 bits
b'4o\xbf\xc6'
>>> 0xc6bf6f34.to_bytes(4, 'little') == b'\x34\x6f\xbf\xc6'
True
否则,您可以struct.pack
使用<I
格式(<
:little-endian,I
:4字节无符号整数,请参阅Format strings - struct
module doc) :
>>> import struct
>>> struct.pack('<I', 0xc6bf6f34)
b'4o\xbf\xc6'
更新/注意:如果您想获得big-endian(或network-endian),则应使用'big'
指定int.to_bytes
:
0xc6bf6f34.to_bytes(4, 'big') # == b'\xc6\xbf\x6f\x34'
和>
或!
与struct.pack
:
struct.pack('>I', 0xc6bf6f34) # == b'\xc6\xbf\x6f\x34' big-endian
struct.pack('!I', 0xc6bf6f34) # == b'\xc6\xbf\x6f\x34' network (= big-endian)