Converting an integer to a bytes object in Python 3 results in a "Q" in PyCharm Debugger?

85 Views Asked by At

I am writing a function to implement a LFSR in Python 3. I've figured out the hard part, which is actually stepping through the state using the feedback value to get the key and getting all of the output bytes by ANDing the key and the input data. To make it easier to do bit shifts and OR and XOR operations, I did all of my operations on integers and saved the result as an integer, however, the function requires a return type of bytes. I have been doing some Googling of my own, and it seems like an accepted way to convert an integer to a bytes object is to do something like result_bytes = result_bytes.to_bytes((result_bytes.bit_length() + 7) // 8, 'big'). Running hex_result_bytes = hex(result_bytes) (mind you, in this context, result_bytes is still currently an integer) and my result_bytes is an integer with a value of 3187993425, I get a str result of "0xbe04eb51", so clearly I should expect a bytes object that looks like b'\xbe\x04\xeb\x51'.

After running result_bytes = result_bytes.to_bytes((result_bytes.bit_length() + 7) // 8, 'big'), I should expect b'\xbe\x04\xeb\x51'. Instead, the result I get is b'\xbe\x04\xebQ' in the PyCharm debugger. Is there something obvious that I am missing here? I don't even know how I got Q because Q is clearly not something that you can get as a hexadecimal byte.

1

There are 1 best solutions below

0
brainyclown10 On

I'm not sure why the PyCharm debugger does this, but it seems to be converting part of the binary string to ASCII. I ran an expression to see if b'\xbe\x04\xebQ' == b'\xbe\x04\xeb\x51', and it evaluates to True. 51 in hex corresponds to Q in ASCII. Another binary string that I am working with right now should be b'\x48\xDC\x40\xD1\x4C', but it is also converting part of it into ASCII and showing it as b'H\xdc@\xd1L', where hex 48 corresponds to H in ASCII, hex 40 corresponds to @ in ASCII, and hex 4C corresponds to L in ASCII