How do I print literal bytes in python?

1

I have this little script to encode and decode a header

HEADER_LENGTH = 4

class Header:
    def encode(length: int, isRequest: bool):
        if length > 0x7fffffff:
            raise ValueError("length too big to handle")

        byteList = [(isRequest << 7) + ((length >> 24) & 0x7f), (length >> 16) & 0xff ,(length >> 8) & 0xff, (length) & 0xff]
        return byteList

    def decode(head):
        isRequest = bool(head[0] & 0x80)

        byteList = [head[0] & 0x7f]
        for i in range(1, HEADER_LENGTH):
            byteList.append(head[i] & 0xff)

        return (isRequest, byteList)

n = int(input("number: "))
r = bool(input("is request: "))

encoded = Header.encode(n, isRequest)
print(f"encoded: {encoded}; bytes: {bytes(encoded)}")
decoded = Header.decode(bytes(encoded)) #I transform them into bytes because this is a test script and the input is this one
print(f"is request: {decoded[0]}; decoded: {decoded[1]}")

but when I insert as input the number 123456789 and request to False I get as response the following output:

encoded: [7, 91, 205, 21]; bytes: b'\x07[\xcd\x15'
is request: False; decoded: [7, 91, 205, 21]

which is all correct, except for that b'\x07[\xcd\x15' that should be b'\x07\x5b\xcd\x15' and I don't know why it converts to that [, it doesn't do this only with the value 0x5b but with (apparently) all values that represent some printable character, I tried everything to make it print only the literal byte but nothing, am I doing something wrong? How can I make sure that it will print only the literal byte?

python-3.x
string
hex
byte
asked on Stack Overflow Jan 1, 2021 by Ax34

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0