gpt4 book ai didi

python - 如何将 32 位整数编码为字节数组?

转载 作者:行者123 更新时间:2023-12-05 01:44:51 24 4
gpt4 key购买 nike

我需要像这样通过串行连接发送一个 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

最佳答案

如果您使用的是 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格式(<:小端,I:4 字节无符号整数,请参阅 Format strings - struct module doc):

>>> import struct
>>> struct.pack('<I', 0xc6bf6f34)
b'4o\xbf\xc6'

更新/注意:如果你想获得大端(或网络端),你应该指定'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)

关于python - 如何将 32 位整数编码为字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44571093/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com