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?
-
6[They always have the same behavior.](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=d37ee7c0e9cee2ecfca099ff5ac6465d) Endianness that you can actually observe is defined on the byte level, and there is just one way to order a single byte. – user4815162342 Jan 31 '22 at 15:26
-
3As @user4815162342 said, they have the same behaviour. The reason why both exist is because they are [generated by a macro](https://doc.rust-lang.org/1.54.0/src/core/num/mod.rs.html#161-162) which is also used for larger integer types where the LE/BE distinction is meaningful. – Jmb Jan 31 '22 at 15:35
-
18`..le_bytes` is obviously the french version – Grajdeanu Alex Feb 01 '22 at 08:23
2 Answers
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
.

- 25,033
- 7
- 51
- 90
-
Also, if/when a trait is ever introduced for these things, `u8` would still need to implement these functions. In its case, trivially. – GManNickG Feb 01 '22 at 04:35
-
1Funnily, [they're implementing using macro in std](https://doc.rust-lang.org/stable/src/core/num/mod.rs.html#267-268)... – Chayim Friedman Feb 01 '22 at 10:42
On a byte-level there is no difference. To better understand how Big-endian differs from Little-endian, consider this:
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.

- 8,726
- 26
- 46
-
Language agnostic, but assuming 8-bit bytes. Fairly common nowadays... – Deduplicator Feb 01 '22 at 00:26
-