Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python bytes representation

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

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'

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?

like image 940
poul1x Avatar asked Sep 13 '25 20:09

poul1x


1 Answers

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

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

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

Hope this helps.

like image 146
Andrew McDowell Avatar answered Sep 17 '25 21:09

Andrew McDowell