2

As part of an exercise to play with binary and ascii formats, I wrote the integer 49 to a file using a C program. In binary, its 4 byte representation is

00000000 00000000 00000000 00110001

In ascii, the first 3 bytes are null bytes (displayed as ^@), and the last byte is the character 1. When I opened this in vim, I expected to see three null bytes, followed by 1. Instead, I saw it reversed, that is, 1 followed by three null bytes. Why is it so?

Korizon
  • 3,677
  • 7
  • 37
  • 52

1 Answers1

2

It seem that your platform is little-endian (all x86 are little-endian) that stores bytes low to high, so 49 in memory is stored as

00110001 00000000 00000000 00000000

instead of what you have expected.


If you want to display it in format that you expect you need to save it using big-endian (also known as network byte order) using htonl() function.

Hauleth
  • 22,873
  • 4
  • 61
  • 112
  • When I read back the integer via a C code, it correctly reads back 49 irrespective of the endianness and the layout in memory. I guess when a text editor reads it, it just displays the bytes laid out in memory and does not know about endianness. – Korizon Aug 09 '17 at 00:52
  • 1
    Not quite. If you would read your integer on machine with different endiannes you would receive different result. That is why there is defined network byte order, so it would be interoperable between architectures. – Hauleth Aug 09 '17 at 07:30