406. How can a program check whether the machine is little-endian or big-endian?
EasyAlgorithm analysis
Show model answer
Store a multi-byte integer whose bytes differ, such as the 32-bit value 1, and look at the byte at the lowest address. If that byte is 1, the least significant byte comes first: little-endian (x86 and most ARM configurations). If it is 0, the machine is big-endian. In C, cast the address of an `int` to `unsigned char *` and read the first byte; in JavaScript, `new Uint8Array(new Uint32Array([1]).buffer)[0] === 1` means little-endian; Python exposes `sys.byteorder`.
Endianness matters when serialising binary data, reading file formats or talking over networks (network byte order is big-endian, hence `htonl`/`ntohl`). Portable code avoids the question by assembling values from bytes with shifts, which behaves the same on every machine.