Python 3构建字节数组 [英] Python 3 Building an array of bytes

查看:196
本文介绍了Python 3构建字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用原始二进制数据构建一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆