问题描述
我正在尝试制作将通过UDP发送的字节帧.我有一个框架类,该类具有以下属性:同步, frameSize ,数据,校验和等我使用十六进制字符串表示值.像这样:
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'\xaa\x01\x004D\x856\x00\xd4?'
因此,第一个单词可以正确转换(AA01-> \ xaa \ x01),但是(0034-> \ x004D)是不一样的.我尝试使用 bytearray.fromhex ,因为我可以在字节之间使用空格,但得到的结果相同.您能帮我通过UDP发送相同的十六进制单词吗?
So, first word is converted ok (AA01 -> \xaa\x01) 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字符的任何字节. 4
与 \ x34
相同,但是它选择在表示中打印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
确实与 \ x00 \ x34
相同, D \ x856 \ x00
与 \x44 \ x85 \ x36 \ x00
和 \ xd4?
与 \ xd4 \ x3f
相同,因为:
So \x004
is really the same as \x00\x34
, D\x856\x00
is the same as \x44\x85\x36\x00
, and \xd4?
is the same as \xd4\x3f
, 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.
如果有帮助,您可以使用 binascii.hexlify()
:
If it helps, you can visualise the bytes
values as hex again using binascii.hexlify()
:
>>> import binascii
>>> binascii.hexlify(b'\xaa\x01\x004D\x856\x00\xd4?')
b'aa01003444853600d43f'
,您会看到 4
, D
, 6
和?
再次由正确的十六进制字符.
and you'll see that 4
, D
, 6
and ?
are once again represented by the correct hexadecimal characters.
这篇关于Python:将十六进制字符串转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!