How to Programmatically Check Endianness in Linux: C, Python & Bash Methods


2 views

Determining a system's byte order (endianness) is crucial for low-level programming, networking protocols, and binary data processing. Here are multiple reliable methods to check endianness programmatically:

The simplest way to check endianness is through system commands:

lscpu | grep "Byte Order"
# Sample output:
# Byte Order:          Little Endian

For programmatic detection in C, use this portable method:

#include 
#include 

int main() {
    uint32_t x = 0x01234567;
    char *c = (char*) &x;
    printf(*c == 0x67 ? "Little Endian\\n" : "Big Endian\\n");
    return 0;
}

Python provides a clean way to check endianness:

import sys
print(sys.byteorder)
# Outputs: 'little' or 'big'

Or using struct module:

import struct
print("Little" if struct.pack('@h', 1) == b'\\x01\\x00' else "Big")

For shell scripting environments:

echo -n I | od -to2 | head -n1 | cut -f2 -d" " | cut -c6
# Outputs 1 (Little) or 0 (Big)

Some ARM systems show endianness here:

grep -q "little endian" /proc/cpuinfo && echo "Little" || echo "Big"

Common architectures and their typical endianness:

  • x86/x86_64: Little Endian
  • ARM: Bi-endian (usually Little by default)
  • PowerPC: Big Endian
  • MIPS: Configurable

For production code, consider these factors:

# Portable C++ approach using constexpr
constexpr bool is_little_endian() {
    const uint32_t x = 0x01;
    return reinterpret_cast(&x)[0] == 0x01;
}

Endianness refers to the byte order a CPU uses to store multibyte data in memory. In Linux environments, you might encounter both:

  • Big Endian: Most significant byte first (e.g., PowerPC, SPARC)
  • Little Endian: Least significant byte first (e.g., x86, x86_64, ARM)

The simplest way to check endianness is using the lscpu command:

lscpu | grep -i endian
Byte Order:            Little Endian

Alternatively, use uname with processor architecture:

uname -m

Here's a reliable bash function to detect endianness:

is_big_endian() {
    local hexdump=$(echo -n I | hexdump -o | awk '{print substr($2,6,1); exit}')
    [[ $hexdump == "0" ]] && echo "Little Endian" || echo "Big Endian"
}

Or using od command:

echo -n -e "\x01\x00" | od -d | head -n1 | awk '{print $2;exit}' | grep -q 1 && echo "LE" || echo "BE"

Python's sys module provides a straightforward way:

import sys
print("Little Endian" if sys.byteorder == "little" else "Big Endian")

For a more low-level approach:

import struct
print("Little Endian" if struct.pack('@h', 1) == b'\x01\x00' else "Big Endian")

For embedded Linux development, this C snippet works well:

#include 
int main() {
    unsigned int i = 1;
    char *c = (char*)&i;
    printf(*c ? "Little Endian\n" : "Big Endian\n");
    return 0;
}

When writing portable code, consider:

  • Network operations (always convert to network byte order)
  • Binary file formats (specify endianness in documentation)
  • Data exchange between different architectures