Check if System is Little Endian or Big Endian using C++

Check if System is Little Endian or Big Endian using C++

Understanding the endianness of a system is crucial in software development, especially when dealing with data serialization, network communication, and hardware interfacing. Endianness refers to the order in which bytes are stored in memory. This tutorial explains how to check if a system is little endian or big endian using C++.

This following code snippet checks the endianness of the system by first initializing an integer variable with the value 1. It then casts the address of this integer variable to a pointer to a char type. By dereferencing this pointer and comparing it to 1, the code determines whether the least significant byte (LSB) of the integer is stored at the lowest memory address, indicating little endian, or not, indicating big endian.

#include <iostream>

int main()
{
    int val = 1;
    if (*(char *) &val == 1) {
        std::cout << "Little endian" << std::endl;
    } else {
        std::cout << "Big endian" << std::endl;
    }

    return 0;
}

Leave a Comment

Cancel reply

Your email address will not be published.