Python字节表示 [英] Python bytes representation

查看:79
本文介绍了Python字节表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing a hex viewer on python for examining raw packet bytes. I use dpkt module.

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

I supposed that one hex byte may have value between 0x00 and 0xFF. However, I've noticed that python bytes representation looks differently:

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

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

I don't understand what do these symbols mean. How can I translate these symbols to original 1-byte values which could be shown in hex viewer?

推荐答案

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

The \xhh indicates a hex value of hh. i.e. it is the Python 3 way of encoding 0xhh.

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

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

The b at the start of the string is an indication that the variables should be of bytes type rather than str. The above link also covers that. The \n is a newline character.

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

You can use bytearray to store and access the data. Here's an example using the byte string in your question.

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

希望这会有所帮助.

这篇关于Python字节表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆