gpt4 book ai didi

Python 3 构建字节数组

转载 作者:IT老高 更新时间:2023-10-28 21:51:02 24 4
gpt4 key购买 nike

我需要使用原始二进制数据构建一个 tcp 框架,但我发现的所有关于字节的示例和教程都涉及从字符串转换,这不是我需要的。

简而言之,我只需要构建一个字节数组:

0xA2 0x01 0x02 0x03 0x04

请注意,我来自 C/C++ 世界。

我试过了:

frame = b""
frame += bytes( int('0xA2',16) )
frame += bytes( int('0x01',16) )
frame += bytes( int('0x02',16) )
frame += bytes( int('0x03',16) )
frame += bytes( int('0x04',16) )

然后,将此帧变量扔给套接字的发送方法,但由于帧不包含我想要的内容而无法按预期工作...

我知道这是一个关于 Python 的非常基本的问题,所以如果你能指出我正确的方向......

最佳答案

使用 bytearray :

>>> frame = bytearray()
>>> frame.append(0xA2)
>>> frame.append(0x01)
>>> frame.append(0x02)
>>> frame.append(0x03)
>>> frame.append(0x04)
>>> frame
bytearray(b'\xa2\x01\x02\x03\x04')

或者,使用您的代码但修复错误:

frame = b""
frame += b'\xA2'
frame += b'\x01'
frame += b'\x02'
frame += b'\x03'
frame += b'\x04'

关于Python 3 构建字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7555689/

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