endianness
termoGuardado neste navegador · Minha bancada
Significa: byte order: big-endian (most significant byte first) or little-endian (least significant byte first)
A ordem em que um processador, um formato de arquivo ou um protocolo distribui os bytes de um número com mais de um byte: big-endian põe o byte mais significativo no endereço mais baixo, little-endian põe ali o menos significativo.
Danny Cohen deu nome às duas ordens em 1980, a partir da guerra dos ovos das Viagens de Gulliver. Os headers da internet são big-endian, como diz a RFC 791, e o POSIX chama isso de network byte order, a ordem de rede; o x86-64 e a maioria dos sistemas Arm são little-endian; o IBM z é big-endian; Power, RISC-V, MIPS e SPARC rodam nas duas ordens, o que se chama bi-endian. O código converte em cada fronteira com htonl, ntohs e as parentes delas, e uma conversão esquecida produz um número válido e errado, não um erro: a porta 80 gravada na ordem do host numa máquina little-endian é lida da rede como a porta 20480.
O que é. O valor de 32 bits 0x0A0B0C0D fica guardado como os bytes 0A 0B 0C 0D numa máquina big-endian e como 0D 0C 0B 0A numa little-endian. O POSIX define as duas: na representação little-endian o primeiro byte é o menos significativo, e a significância cresce com o endereço; na big-endian o primeiro byte é o mais significativo. Só números com mais de um byte são afetados: bytes isolados, texto ASCII e UTF-8 ficam iguais nas duas ordens, e a ordem dos bits dentro de um byte é assunto da camada de enlace, não do software (a RFC 2469 registra que o Ethernet leva o primeiro bit de cada byte no fio para o bit menos significativo dele, e que o Token Ring fazia o contrário).
Onde a ordem é fixa. O manual da Intel chama os processadores Intel 64 e IA-32 de little endian machines, e a z/Architecture da IBM endereça um campo pelo byte mais à esquerda, o de mais alta ordem. A Power ISA deixa o sistema operacional escolher a ordem com um único bit de modo; o RISC-V define variantes little-endian, big-endian e bi-endian, mas guarda as instruções sempre em parcelas little-endian; o SPARC V9 é big-endian por padrão, com acessos a dados little-endian; o Linux descreve os sistemas MIPS como montados para uma ordem ou para a outra. Entre os formatos, os headers da internet, o PNG, os arquivos class do Java, o XDR (External Data Representation) e o CBOR são big-endian; o BMP e a memória do WebAssembly são little-endian; o TIFF marca a ordem com II ou MM, o ELF com o byte EI_DATA, e o texto UTF-16 com um byte order mark, sem o qual o padrão Unicode e a RFC 2781 o leem como big-endian, enquanto os navegadores, seguindo o Encoding Standard do WHATWG, entendem o rótulo utf-16 como UTF-16LE.
A conversão. As conversões são baratas e têm o nome da direção: htonl e ntohl no POSIX, htobe32 e le32toh no endian.h mais recente dele, cpu_to_be32 no kernel do Linux, o ! e os prefixos de menor e maior no struct do Python. Os processadores trazem instruções para isso: BSWAP e MOVBE no x86, LOAD REVERSED no IBM z, os loads e stores byte-reverse no Power, rev8 na extensão Zbb do RISC-V. Para descobrir o que uma máquina é, o sys.byteorder do Python responde little ou big, e o lscpu imprime uma linha Byte Order.
Por que importa. Nenhuma ordem vence pelo mérito: o memorando de Cohen lista o que os comparadores seriais preferem e o que os somadores seriais preferem, e conclui que concordar com uma ordem importa mais do que qual ordem se escolhe. Os projetistas do RISC-V escolheram little-endian porque domina o mercado, e mantiveram variantes big-endian porque as redes IP trabalham com dados big-endian; a RFC 4506 admite que a ordem única do XDR, big-endian, é injusta com as máquinas little-endian, e argumenta que uma ordem só dispensa qualquer protocolo para ler os dados. O custo de verdade é a conversão em cada fronteira e os bugs quando uma falta: uma porta ou um endereço carregados crus, UTF-16 decodificado na ordem errada, um hash calculado sobre bytes crus. O driver de bonding do Linux faz o hash dos bytes crus dos endereços, então um servidor x86-64 e um guest s390x calculam hashes diferentes para o mesmo fluxo, e com três, cinco, seis ou sete membros muitas vezes mandam esse fluxo por links diferentes.
Também conhecido como: byte order, big-endian, little-endian, bi-endian, network byte order, host byte order, byte swap, byteswap, ordem de bytes, ordem dos bytes, ordem de rede
Fontes
- Danny Cohen, IEN 137, 'On Holy Wars and a Plea for Peace', 1 April 1980 (read 2026-11-08): the names Little-Endians and Big-Endians, consistent orders, the arguments for each, agreeing on an order matters more than which
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), be16toh (read 2026-11-08): the definitions of little-endian and big-endian representation; network byte order is big-endian
- POSIX.1-2024, 4.13 Host and Network Byte Orders (read 2026-11-08): network byte order and host byte order; htonl, htons, ntohl and ntohs
- RFC 791, Internet Protocol, Appendix B (read 2026-11-08): the most significant octet is transmitted first
- RFC 2469, A Caution On The Canonical Ordering Of Link-Layer Addresses (read 2026-11-08): Ethernet and Token Ring bit order
- Intel 64 and IA-32 Architectures Software Developer's Manual, volume 1, 253665-084US (read 2026-11-08): little endian machines; BSWAP and MOVBE
- IBM z/Architecture Principles of Operation, SA22-7832-13 (read 2026-11-08): a group of bytes addressed by its leftmost byte; LOAD REVERSED
- OpenPOWER Foundation, Power ISA Version 3.1C (read 2026-11-08): the Endian mode specified by the operating system; byte-reverse instructions
- RISC-V Instruction Set Manual, unprivileged, intro.adoc (read 2026-11-08): little-endian, big-endian and bi-endian variants; little-endian instruction parcels; why little-endian was chosen
- SPARC International, The SPARC Architecture Manual, Version 9 (read 2026-11-08): big-endian by default, little-endian data accesses
- The Linux kernel, arch/mips/Kconfig (read 2026-11-08): MIPS machines configured for either byte order
- RFC 4506, XDR: External Data Representation Standard (read 2026-11-08): one big-endian byte order, and why
- The Unicode Standard 18.0.0, chapter 3, D98 (read 2026-11-08): the UTF-16 encoding scheme is big-endian when there is no byte order mark
- WHATWG Encoding Standard (read 2026-11-08): the label utf-16 names UTF-16LE
- The Linux kernel, drivers/net/bonding/bond_main.c (read 2026-11-08): the transmit hash over raw address bytes
- Python documentation, sys.byteorder (read 2026-11-08)
- Python documentation, struct (read 2026-11-08): Intel x86, AMD64 (x86-64) and Apple M1 are little-endian; IBM z is big-endian; the ! prefix is network order
- Debian wiki, ArchitectureSpecificsMemo: the endianness of each Debian port (read in a browser on 2026-11-08: the site refuses automated reads)
- util-linux, sys-utils/lscpu.c (read 2026-11-08): the Byte Order line
- The Linux kernel, include/linux/byteorder/generic.h (read 2026-11-08): cpu_to_be32 and the other conversions
- RISC-V Instruction Set Manual, zbb.adoc (read 2026-11-08): rev8 reverses the byte order of a register
- W3C, PNG Specification, Third Edition, 7.1 (read 2026-11-08): integers in network byte order
- Oracle, The Java Virtual Machine Specification, Java SE 25, chapter 4 (read 2026-11-08): multibyte data items in big-endian order
- RFC 8949, CBOR (read 2026-11-08): multi-byte values in network byte order
- Microsoft Learn, BITMAPFILEHEADER (read 2026-11-08): bfType must be 0x4d42, the ASCII string BM
- WebAssembly 3.0 specification, instructions (read 2026-11-08): memory values read and written in little endian byte order
- Aldus, TIFF Revision 6.0, 1992, as hosted by the ITU (read 2026-11-08): II and MM; readers must handle both
- System V ABI, generic ABI, ELF header (read 2026-11-08): EI_DATA, ELFDATA2LSB and ELFDATA2MSB
- RFC 2781, UTF-16, an encoding of ISO 10646 (read 2026-11-08): text without a byte order mark should be read as big-endian