Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 962
mpls Avatar asked Sep 13 '25 07:09

mpls


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.

like image 114
trent Avatar answered Sep 14 '25 22:09

trent


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.

like image 35
at54321 Avatar answered Sep 14 '25 22:09

at54321