我想说,这段代码将提供三次相同的输出,但它没有:
import crcmod
#create CRC16 calculator
crc16 = crcmod.predefined.mkCrcFun('crc-16')
#wait for user input
#hstr = raw_input("enter hex commands, space separated: ")
hstr = '81 12 C0 00 01 05'
hex_series = hstr.replace(' ', '\\x')
hex_series_caps = hstr.capitalize().replace(' ', '\\x') #why is there difference?
print hex(crc16(hex_series)) # gives 0xd795 incorrect! + how can there be a 9???
print hex(crc16(hex_series_caps)) # gives 0x37b4 incorrect!
print hex(crc16('\x81\x12\xC0\x00\x01\x05')) # gives 0x815b correct!
请解释一下!在
一旦将问题放入python控制台并查看数据,问题就会暴露出来:
主要的问题是,您将\x符号按字面形式放入其中,而在第一个好的字符串中,它被翻译成-\xbla具有特殊的含义,当您输入字符串时,它会被翻译,在字符串中斜杠后跟x只是一个斜杠后接x。(第二个问题是,即使这样做有效,因为您替换了空格,第一个不会被转换)。在
python在底部用\\in\\xc0表示的是“这是一个普通的斜杠”。在
让我们打开一个Python提示符。。。在
如您所见,没有一个字符串是您想要的字符串。用
"\\x"
替换空格只需在字符串中插入一堆反斜杠和x
字符,它不会进行任何转义。在像
^{pr2}$'\x63'
这样的转义序列将变成'c'
,但是只有在源代码中以这种方式编写时才是。转义序列不会在字符串操作、读取字符串或几乎任何其他操作之后发生。例如试试这个:
乔所说的是正确的,所以我不再重复了。要正确转换输入字符串,可以使用以下命令:
编辑:尽管使用Dietrich Epp所示的
base64.b16decode()
更优雅相关问题 更多 >
编程相关推荐