(More or less) analogous to how the int
type knows how to convert an integer instance to bytes, it is int
again who knows how to convert bytes back to an integer.
Your xbytes
variable is a bytes
object, so it doesn't know how to convert itself to an integer.
Instead you do it like this:
intermediate_result = int.from_bytes(xbytes, byteorder='big')
(And afterwards you will want to convert it into a string of 0s and 1s.)
The reason it's not completely orthogonal (Converting forward you use value.method()
and converting back you use type.method(value)
) is that in the forward case your value is already of the type which knows how to convert itself, but in the backward case, your value is of the other type, who doesn't know how to convert back.
You can also think about it in English terms, if you like:
value.to_bytes(byteorder='big')
would be Convert this integer "value" to a bytes object.
int.from_bytes(value, byteorder='big')
would be Create a fresh integer object from that bytes "value".