Stream: beginners

Topic: U32 endiannes conversion?


view this post on Zulip Matthieu Pizenberg (May 24 2024 at 14:07):

What’s the simplest and/or most efficient way to convert a U32 (big endian by default) into its little endian equivalent?

view this post on Zulip Matthieu Pizenberg (May 24 2024 at 14:20):

For now, I’ve written the following:

littleendian : U32 -> U32
littleendian = \b ->
    b3 = Num.shiftRightZfBy b 24
    b2 = Num.shiftRightZfBy (Num.shiftLeftBy b 8) 24
    b1 = Num.shiftRightZfBy (Num.shiftLeftBy b 16) 24
    b0 = Num.shiftRightZfBy (Num.shiftLeftBy b 24) 24
    Num.shiftLeftBy b0 24 + Num.shiftLeftBy b1 16 + Num.shiftLeftBy b2 8 + b3

view this post on Zulip Brendan Hansknecht (May 24 2024 at 14:29):

Yeah, bit shifting is the way. Personally, I prefer bitwise or to addition, but would need to play around with exact assembly to find the fastest way (and tight benchmarks).

view this post on Zulip Brendan Hansknecht (May 24 2024 at 14:30):

Also, I would expect bitwise and with 0xFF to be more likely to optimize correctly than shifting back and forth. But again, just a guess and llvm is really smart.

view this post on Zulip Matthieu Pizenberg (May 24 2024 at 14:32):

Thanks, yeah the performance part is just out of curiosity. I’m implementing salsa20 for the learning experience and not for production ready code.


Last updated: Jul 06 2025 at 12:14 UTC