mmcblk1
mmcblk1

Reputation: 168

Python int to bytes conversion error with some values

I am using the int.to_bytes method within Python to convert integer values into bytes.

With certain values, this seems to fail. Attached is the output from the Python console:

value = 2050
value.to_bytes(2, 'big')
>>> b'\x08\x02'
value = 2082
value.to_bytes(2, 'big')
>>> b'\x08"'

With a value of 2050, the conversion seems to be correct. But when the value is 2082, for some reason only the upper byte seems to be extracted. Any reason as to why this is happening?

Upvotes: 0

Views: 571

Answers (1)

pho
pho

Reputation: 25489

It extracts all bytes. Try

value = 2082
x = value.to_bytes(2, 'big')
print(x[0]) # Output: 8
print(x[1]) # Output: 34

When you convert to string, byte 34 translates to ASCII ", which is what you see.

Upvotes: 2

Related Questions