1

I am wanting to use hexadecimal values when working with bytes. However I'm not quite sure on how this is done. For instance:

>>> bytearray([0x10,0x20,0x30])
bytearray(b'\x10 0')

Why are 0x20 and 0x30 ignored?

2 Answers 2

1

0x20 and 0x30 are not ignored: a bytearray is formatted like ASCII-characters and 0x20 happens to be the ASCII-code for a space (), the same for 0x30 which maps to a zero (0).

This is simply a compact way to represent a binary array. You can read all values and their corresponding characters in this Wikipedia article.

In case the character is not printable, it is formatted as \x?? with ?? the hexadecimal code.

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

Comments

1

They are not ignored. 0x20 is the ASCII codepoint for a space, 0x30 is the digit 0. Both are there in the output, following the \x10 byte.

What you are seeing is the representation of the bytes value, which tries to be as readable as possible. It does so by displaying any byte in the printable ASCII range as that ASCII character. Anything not so representable is shown either as a \xhh escape sequence or a shorter two character \? escape (such as \n for a newline or \t for a tab character).

Note that Python produces an integer value for each 0xhh hex notation; it's nothing more than alternative syntax to produce the same integer value. You could have used decimal notation or octal notation too, and the result would have been the same; you are putting integer values into a list object, from which you then create a bytearray object. The original hex notation is not preserved in this process:

>>> [0x10, 0x20, 0x30]
[16, 32, 48]
>>> bytearray([16, 32, 48])
bytearray(b'\x10 0')
>>> [0o20, 0o40, 0o60]
[16, 32, 48]
>>> bytearray([0o20, 0o40, 0o60])
bytearray(b'\x10 0')

The actual values in the bytearray are still integers anyway; if you index into the object you get the individual byte values:

>>> ba = bytearray([0x10, 0x20, 0x30])
>>> ba
bytearray(b'\x10 0')
>>> ba[1]  # 0x20, the space
32
>>> ba[2]  # 0x30, the 0 digit
48

4 Comments

Could you also possibly show me how to treat a bytearray as a stream, such as x = bytearray([0x10,0x20,0x30]) and x.read(1) = 16, x.read(1) = 32
@ritch: use io.BytesIO() instead if you need a byte stream.
@ritch: so x = io.BytesIO(bytes([0x10, 0x20, 0x30])), then x.read(1), etc.
I have been doing that - I do b = x.read(1) and then do print b i get blank. How do I get it store numeric value not ascii representation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.