2
\$\begingroup\$

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?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked May 31, 2019 at 4:37
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

To calculate number of bytes, better use:

numbytes = math.ceil(value.bit_length() / 8)

And then you can just:

def be_to_le(value: int) -> int:
 numbytes = math.ceil(value.bit_length() / 8)
 return int.from_bytes(value.to_bytes(numbytes, byteorder="little"), byteorder="big")
answered May 31, 2019 at 16:26
\$\endgroup\$
1
  • \$\begingroup\$ Ooohhh... so int has a bit_length() method? That's news to me... Thanks for telling me that! I'll probably not use math.ceil though. (n + 7) >> 3 might be better since it keeps everything in int land. Anyways, thanks! \$\endgroup\$ Commented Jun 14, 2019 at 17:50

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.