SQLite Forum

Endianness help
[Larry's right](/forumpost/4cc0a07c03): the bits are *not* flipped end for end in a byte as part of endianness. That concept only covers the order of bytes in a word.

It doesn't even make sense in typical computers to talk about which bit is on the "left" in RAM. The only way you see it as a programmer is the way you'd write the number on paper, least significant digit on the right.

Beyond that, you have to get into [DRAM array structures][1], where you find that bits aren't "to the left" of others at all, but in 2D arrays of strobed columns and rows.

> why does drh feel the need to store ints in big endian format...

Because when SQLite was designed, big-endian processors were far more common than they are now, and the most infulential standards for how you store multi-byte words were set by Sun Microsystems, who was a major champion of big-endian architectures. (68k to start, SPARC later.)

Those key standards were the BSD sockets API with its [`ntohs()` and `htonl()`][2] family functions and [XDR][3], underpinning Sun's highly-successful NFS protocol. This set the so-called "network byte order," which is now arguably backwards, but we're stuck with it now.

> if the storage device & processor will do it for him

I think you're reading too much into the others' comments to say it that way.

The whole point of caring about endianness is that the processor has only a single mode.

Some processors can switch modes, but they run in only one mode at a time. Generally speaking, it's set once early in the system's boot and never changed.

Given that we expect a SQLite DB to work on big- and little-endian processors, SQLite has to pick a mode and stick with it. drh could have chosen to store words in the order used by the machine that created it, requiring twice the code for making conversions and a bunch of conditional code to switch between them, but instead he just picked big-endian, probably for the "network byte order" reasons above.

[1]: https://en.wikipedia.org/wiki/Dynamic_random-access_memory#Array_structures
[2]: https://linux.die.net/man/3/ntohs
[3]: https://en.wikipedia.org/wiki/External_Data_Representation