I have a need to convert wire encoding (big-endian) to little-endian in Python.
The conversion needs to happen as a separate function; I am not allowed to change the function that reads the byte stream because it will break a lot of other functions.
The best I can think of is this:
def be_to_le(value: int) -> int:
assert isinstance(value, int)
numbytes = len(f"0{value:x}") >> 1
if numbytes == 1:
return value
rslt = 0
for b in value.to_bytes(numbytes, byteorder="little"):
rslt <<= 8
rslt |= b
return rslt
Is there a better way?