ioerroror
ioerroror

Reputation: 23

Convert back from int to byte

How would I go about doing the inverse for the following; I converted bytes to integers but now I need to go back to the original byte value.

 bytevalues = int.from_bytes(bytevalues, byteorder='big')

Upvotes: 2

Views: 11524

Answers (1)

James Mchugh
James Mchugh

Reputation: 1014

You can accomplish this using the int to_bytes method. Here is an example:

value = int.from_bytes(bytevalues, byteorder='big') 
new_bytevalues = value.to_bytes(length=len(bytevalues), byteorder='big') 
print(new_bytevalues == bytevalues) # prints True

In to_bytes, we have to define length to be at least the size of the original bytes object. If it is not, it will cause an OverflowError. It can be bigger than the length of the original bytes object, and in that case it will just pad the result with zeros.

Upvotes: 6

Related Questions