bitlvl
EN

Endianness converter

Enter a value and a width. You get both byte orders, the bytes as they would be written to memory or a packet, and the code to swap them.

Width
Input is
 
  

What endianness is

A multi-byte number has to be stored one byte at a time, and there are two sensible orders. Big-endian puts the most significant byte at the lowest address, the way we write numbers: 0x12345678 becomes 12 34 56 78. Little-endian puts the least significant byte first: 78 56 34 12. x86, x86-64 and (by default) ARM are little-endian; network protocols (IP, TCP, DNS), Java class files, PNG and most big-iron formats are big-endian, which is why “network byte order” means big-endian.

When it matters

Inside one program on one machine, never: the CPU handles it. It matters the moment bytes cross a boundary: writing a struct to a file, reading a packet, talking to a sensor over SPI, mapping a binary file format, or interpreting a hex dump. Reading 78 56 34 12 in a dump of x86 memory and thinking it means 0x78563412 is the classic mistake.

The functions

LanguageHost → network (big-endian)Arbitrary swap
Chtonl, htons, htobe64__builtin_bswap32
Gobinary.BigEndian.PutUint32bits.ReverseBytes32
Pythonstruct.pack('>I', x)x.to_bytes(4, 'little')
Rustx.to_be_bytes()x.swap_bytes()
JavaScriptDataView.setUint32(o, x)DataView with littleEndian=true

UTF-16 and the BOM

Text in UTF-16 has the same problem, which is why files may start with a byte order mark: FE FF for big-endian, FF FE for little-endian. UTF-8 has no byte order and needs no BOM.

Questions

Which endianness does my computer use?

Almost certainly little-endian: all x86 and x86-64 CPUs are, and ARM (phones, Apple Silicon, Raspberry Pi) runs little-endian in practice. Big-endian survives in network protocols, some embedded and mainframe systems (s390x, older PowerPC, SPARC).

Why is the network big-endian?

Historical convention from the early ARPANET and IBM/Motorola machines, written into RFC 1700. Every protocol since has followed it, so every socket API has htons/htonl.

Does endianness affect bits inside a byte?

No. A byte is always read as a whole. Bit order only comes up in serial protocols and some CRC algorithms, and is a separate question.

How do I detect endianness at runtime?

Store 1 in a 32-bit integer and look at the first byte: 1 means little-endian. In practice, prefer explicit conversion functions so the code works everywhere.

What is middle-endian?

The PDP-11 stored 32-bit values as two little-endian 16-bit halves in big-endian order (34 12 78 56). It is extinct, but the term is still used for date formats like MM-DD-YYYY.