Detect the CPU's Endianness
Write int is_little_endian(void) that returns 1 if the CPU stores multi-byte values little-endian and 0 if big-endian, by inspecting how a known value is laid out in memory.
The online compiler runs on x86-64, which is little-endian, so the test expects 1.
Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Store a value whose bytes are all different, such as 0x12345678, then look at the byte at the lowest address through an unsigned char pointer.
#include <stdio.h>
#include <stdint.h>
int is_little_endian(void)
{
uint32_t x = 0x12345678u;
const unsigned char *p = (const unsigned char *)&x;
return p[0] == 0x78; /* lowest address holds the least significant byte */
}
Your program is correct. Accessing an object through unsigned char * is always allowed in C, so this is portable and has no strict-aliasing problem.
How 0x12345678 is laid out
| address | little-endian | big-endian |
|---|---|---|
| p[0] | 0x78 | 0x12 |
| p[1] | 0x56 | 0x34 |
| p[2] | 0x34 | 0x56 |
| p[3] | 0x12 | 0x78 |
Other ways to answer:
- A union: union { uint32_t u; uint8_t b[4]; } v = { 0x01 }; return v.b[0]; (fine in C, not in C++).
- At compile time with GCC/Clang: #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__. This is better in real firmware because it costs nothing at run time.
The point interviewers want you to make: you rarely need to detect endianness. When you parse a protocol or file format, build values from bytes with shifts, for example (uint32_t)b[0] << 24 | b[1] << 16 | b[2] << 8 | b[3] for big-endian data. That works on any CPU without checking anything (see Swap Byte Order of a 32-bit Value).
Where it matters: network byte order is big-endian (htonl/ntohl); CAN signals, Modbus registers and many sensors use big-endian fields; x86, RISC-V and almost all Arm systems run little-endian; some PowerPC and older networking chips are big-endian.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
CHECK(is_little_endian() == 1); /* x86-64 and almost all Arm systems */
CHECK(is_little_endian() == is_little_endian());
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}