Python字符串转义的十六进制 [英] Python String to Escaped Hex
问题描述
下面有一些python代码,我设法拼凑起来以实现所需的功能,但是对于python来说,它是一个新手,我认为应该有一个比这里的解决方案优雅得多的解决方案.
I have some python code below I managed to cobble together to achieve what I needed, but being quite new to python I believe there should be a much more elegant solution than the one I have here.
基本上,我需要获取一个任意字符串(MAGICSTRING
)并将其每个字符转换为它们的十六进制值,然后将0x00填充到结果十六进制字符串的开头和结尾,最后将末尾整个填充字符串的长度.然后,我需要这些转义符,以便以后可以将其传递给套接字连接.
Essentially I need to take an arbitrary string (MAGICSTRING
) and convert each of it's characters into their hex value, then pad a 0x00 to the start and end of the resultant hex string, and finally put the hex value of the length of the entire padded string on the end. I then need these escaped so it can be passed to a socket connection later on.
在示例中,MAGICSTRING
为1234,并且'value'的预期结果为'\x00\x31\x32\x33\x34\x00\x06'
In the example, MAGICSTRING
is 1234, and the expected result of 'value' is '\x00\x31\x32\x33\x34\x00\x06'
请参见下面的示例.
MAGICSTRING = '1234'
i=0
hexpass = ''
while i < len(MAGICSTRING):
hexpass = hexpass + hex(ord(MAGICSTRING[i]))[2:]
i += 1
strlen = len(MAGICSTRING) + 2
sendstr = '00'+ hexpass + '00' + '0' + hex(strlen)[2:]
value = sendstr.decode('hex')
赞赏可以对上述内容进行的任何改进.
Appreciate any improvements that can be made to the above.
推荐答案
字符串'1234'
已已经等效于'\x31\x32\x33\x34'
:
>>> '\x31\x32\x33\x34'
'1234'
>>> '\x31\x32\x33\x34' == '1234'
True
因此将其编码为十六进制然后再次解码是..繁忙的工作:
thus encoding that to hex then decoding it again is.. busy work:
>>> '1234'.encode('hex').decode('hex')
'1234'
\xhh
只是一个标记,可以帮助您创建值.当回显字节字符串时,Python始终将直接显示可打印的ASCII字符,而不是使用\xhh
表示法.
\xhh
is just a notation to help you create the values; when echoing a byte string Python will always display printable ASCII characters directly rather than use the \xhh
notation.
此处的十六进制表示法只是表达每个字节的值的一种方法,它实际上是0到255之间的整数.Python字符串中的每个字节都是具有这样约束值的字节,并编码为
Hex notation here is just a way to express the values of each byte, which is really an integer between 0 and 255. Each byte in a Python string is then a byte with such a constrained value, and encoding to the 'hex'
codec produces a string with hex digits for those bytes, and bytes again from the hex digits.
因此,您要做的就是添加\x00
空字节和长度:
As such, all you have to do is add the \x00
null bytes and the length:
MAGICSTRING = '1234'
value = '\x00{}\x00{}'.format(MAGICSTRING, chr(len(MAGICSTRING) + 2))
此处,\xhh
表示法用于产生空字节,而 chr()
函数产生长度字节".
Here the \xhh
notation is used to produce the null bytes, and the chr()
function produces the length 'byte'.
演示:
>>> MAGICSTRING = '1234'
>>> '\x00{}\x00{}'.format(MAGICSTRING, chr(len(MAGICSTRING) + 2))
'\x001234\x00\x06'
>>> '\x00{}\x00{}'.format(MAGICSTRING, chr(len(MAGICSTRING) + 2)) == '\x00\x31\x32\x33\x34\x00\x06'
True
这篇关于Python字符串转义的十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!