Python字节表示

时间:2018-10-07 12:16:22

标签: python-3.x byte representation

我正在python上编写一个十六进制查看器,以检查原始数据包字节。我使用dpkt模块。

我认为一个十六进制字节的值可能在0x00和0xFF之间。但是,我注意到python bytes 表示形式看起来有所不同:

'b .. \ x8a \ n \ x1e + \ x1f \ x84V \ xf2 \ xca $ \ xb1 ...'

我不明白这些符号是什么意思。如何将这些符号转换为可以在十六进制查看器中显示的原始1字节值?

1 个答案:

答案 0 :(得分:0)

\ xhh指示hh的十六进制值。也就是说,这是Python 3编码0xhh的方式。

请参见https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

字符串开头的b表示变量应为字节类型而不是str。上面的链接也涵盖了这一点。 \ n是换行符。

您可以使用字节数组来存储和访问数据。这是在您的问题中使用字节字符串的示例。

example_bytes = b'\x8a\n\x1e+\x1f\x84V\xf2\xca$\xb1'
encoded_array = bytearray(example_bytes)
print(encoded_array)
>>> bytearray(b'\x8a\n\x1e+\x1f\x84V\xf2\xca$\xb1')
# Print the value of \x8a which is 138 in decimal.
print(encoded_array[0])
>>> 138
# Encode value as Hex.
print(hex(encoded_array[0]))
>>> 0x8a

希望这会有所帮助。