4

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?

0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, how can I decode this python-type-encoded sequence to array of hex bytes containing values in range of [0x00 - 0xFF]? I want to get per-byte packet representation. Something like HxD view.
I've not used HxD so not sure exactly what you need but you can use the bytearray class to store and access the sequence. I'll edit my answer with some example code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.