Python: Converting bytearray to bytestring weird results

Viewed 302

I'm appending the number 33 to a bytearray, which works fine but when I am converting the bytearray to a bytestring the number 33 converts to an exclamation mark (!).

Example Code below:

f_bytes = bytearray(b"\xFF\xFF")

f_bytes.append(3)
f_bytes.append(33)
f_bytes.append(12)

byte_msg = bytes(f_bytes)

print(byte_msg)
print (''.join(format(x, '02x') for x in f_bytes))

Here is the output:

b'\xff\xff\x03!\x0c'
ffff03210c

I am expecting the bytestring to look like the bytearray but it doesn't, can someone help me understand the problem?

1 Answers

The 0x00-0x1f, 0x7F and 0xFF of the ASCII table are control characters which control the input/ output of a terminal. They are usually not printed in a non-binary string representation (on your shell they might appear as something like ^C, ^M or ^[[C ..). In contrast to the other bytes 0x33 corresponds to the a literal which is printed in the string. In your second print command you disable the conversion into the exclamation mark literal by using a format string, thus you get the hexadecimal value for all bytes.

Related