Python 3构建字节数组 [英] Python 3 Building an array of bytes
问题描述
我需要使用原始二进制数据构建一个tcp框架,但是我发现谈论字节的所有示例和教程始终涉及从字符串进行转换,而这不是我所需要的.
I need to build a tcp frame with raw binary data, but all examples and tutorials I've found talking about bytes always involve conversion from a string, and that's not what I need.
简而言之,我只需要构建一个字节数组:
In short, I need to build just an array of bytes:
0xA2 0x01 0x02 0x03 0x04
请注意,我来自C/C ++世界.
Please note that I come from C/C++ world.
我已经尝试过了:
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) )
然后,将此框架变量抛出以发送套接字方法,但由于框架不包含我想要的内容而无法按预期工作...
Then, throw this frame variable to send method of socket, but not working as expected as frame doesn't contain what I want...
我知道这是关于Python的一个非常基本的问题,因此,如果您能为我指明正确的方向...
I know this is a very basic question about Python, so if you could point me in the right direction...
推荐答案
使用>
>>> 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')
或者,使用您的代码但纠正错误:
or, using your code but fixing the errors:
frame = b""
frame += b'\xA2'
frame += b'\x01'
frame += b'\x02'
frame += b'\x03'
frame += b'\x04'
这篇关于Python 3构建字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!