Endianness [en]

I found this video very interesting about Endianness and the byte arrangement problem in memory.

Imagine that we have a 32-bit number, 12648430, to store in memory.

0x00c0ffee in hexadecimal

The number contains 4 bytes, so given positions in memory of 1 byte each, we have to place each byte in 4 different positions.

But in which order should we place them?

00 - c0 - ff - ee (Starting with the most significant byte)

or

ee - ff — c0 - 00 (Starting with the least significant byte)

This decision determines the "endianness" of a byte arrangement.

Imagine that we have to read a binary file generated by some other software and display a number to the user.

Simple, right?

We already know in advance that the current number written is 3256548, for example.

Here's a Ruby code to read this file.

rubyCopy codebytes = File.read('message.bin', mode: 'rb') # 1

number = bytes.unpack('V') # 2

puts number
  • 1: We indicate to open the file in raw binary mode; mode: 'rb'

  • 2: We use the unpack method, passing the formatter 'V' to interpret this array of bytes ordering them as little endian (more common).

We run the code... and we get:

3836752128

Hmm. It's not the number we expected (3256548). Why? 🤔

It seems that whoever wrote the file ordered the bytes in reverse, in Big Endian.

Let's change the formatter to Big Endian then. Change V to N.

If we run the code, we will receive exactly what we expected.

3256548

https://www.youtube.com/watch?v=6rNlekLbGjA

https://www.youtube.com/watch?v=ggz24JKI0VQ

https://www.youtube.com/watch?v=LxvFb63OOs8