Python:将 HEX 字符串转换为字节

2022-01-22 00:00:00 python string bytearray hex udp

问题描述

我正在尝试制作将通过 UDP 发送的字节帧.我有 Frame 类,它具有 sync、frameSize、data、checksum 等属性. 我使用十六进制字符串来表示值.像这样:

I'm trying to make byte frame which I will send via UDP. I have class Frame which has attributes sync, frameSize, data, checksum etc. I'm using hex strings for value representation. Like this:

testFrame = Frame("AA01","0034","44853600","D43F")

现在,我需要将这些十六进制值连接在一起并将它们转换为像这样的字节数组?!

Now, I need to concatenate this hex values together and convert them to byte array like this?!

def convertToBits(self):
    stringMessage = self.sync + self.frameSize + self.data + self.chk
    return b16decode(self.stringMessage)

但是当我打印转换后的值时,我没有得到相同的值,或者我不知道正确读取 python 表示法:

But when I print converted value I don't get the same values or I don't know to read python notation correctly:

This is sync: AA01
This is frame size: 0034
This is data:44853600
This is checksum: D43F

b'xaax01x004Dx856x00xd4?'

所以,第一个单词转换正常 (AA01 -> xaax01) 但 (0034 -> x004D) 它不一样.我尝试使用 bytearray.fromhex 因为我可以在字节之间使用空格,但我得到了相同的结果.你能帮我通过 UDP 发送相同的十六进制字吗?

So, first word is converted ok (AA01 -> xaax01) but (0034 -> x004D) it's not the same. I tried to use bytearray.fromhex because I can use spaces between bytes but I got same result. Can you help me to send same hex words via UDP?


解决方案

Python 将任何可以表示可打印 ASCII 字符的字节显示为该字符.4x34 相同,但它选择在表示中打印 ASCII 字符.

Python displays any byte that can represent a printable ASCII character as that character. 4 is the same as x34, but as it opted to print the ASCII character in the representation.

所以 x004 真的和 x00x34 一样,Dx856x00x44x85x36x00,而xd4?xd4x3f相同,因为:

So x004 is really the same as x00x34, Dx856x00 is the same as x44x85x36x00, and xd4? is the same as xd4x3f, because:

>>> b'x34'
'4'
>>> b'x44'
'D'
>>> b'x36'
'6'
>>> b'x3f'
'?'

这只是字节值的表示;该值完全正确,您无需执行任何其他操作.

This is just the representation of the bytes value; the value is entirely correct and you don't need to do anything else.

如果有帮助,您可以使用 bytes 值可视化为十六进制" rel="nofollow">binascii.hexlify():

If it helps, you can visualise the bytes values as hex again using binascii.hexlify():

>>> import binascii
>>> binascii.hexlify(b'xaax01x004Dx856x00xd4?')
b'aa01003444853600d43f'

您会看到 4D6? 再次由正确的十六进制字符.

and you'll see that 4, D, 6 and ? are once again represented by the correct hexadecimal characters.

相关文章