Is there a meaningful difference between u8::from_be_bytes and u8::from_le_bytes?
Asked Answered
C

2

24

Since big-endian and little-endian have to do with byte order, and since one u8 is one byte, wouldn't u8::from_be_bytes and u8::from_le_bytes always have the same behavior?

Chick answered 31/1, 2022 at 15:23 Comment(3)
They always have the same behavior. Endianness that you can actually observe is defined on the byte level, and there is just one way to order a single byte.Rsfsr
As @Rsfsr said, they have the same behaviour. The reason why both exist is because they are generated by a macro which is also used for larger integer types where the LE/BE distinction is meaningful.Garratt
..le_bytes is obviously the french versionBrabble
T
31

Yes, they have the same behavior. The byte-oriented functions (swap_bytes and (from|to)_[bln]e(_bytes)?) on u8 are provided for consistency with the larger integers, even though they have trivial implementations.

Among other things, this makes it easier to write macro code that is correct for all sizes of integer, rather than having to special-case u8.

Tinhorn answered 31/1, 2022 at 15:35 Comment(2)
Also, if/when a trait is ever introduced for these things, u8 would still need to implement these functions. In its case, trivially.Bowen
Funnily, they're implementing using macro in std...Suffix
D
7

On a byte-level there is no difference. To better understand how Big-endian differs from Little-endian, consider this:

Endianness example

As can be seen, we have three bytes in the example, the bits of each having a different color. Notice how the bits in each byte look exactly the same in both BE and LE.

That is language-agnostic BTW.

As for the Rust functions operating on u8, Trent explained it very well. My answer focuses more on the part how BE/LE work in general.

Daleth answered 31/1, 2022 at 15:33 Comment(2)
Language agnostic, but assuming 8-bit bytes. Fairly common nowadays...Chiaroscuro
That would then be octets.Acton

© 2022 - 2024 — McMap. All rights reserved.