What’s the simplest and/or most efficient way to convert a U32 (big endian by default) into its little endian equivalent?
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
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).
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.
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