How to Find Out Whether a Machine is Big Endian or Little Endian in C/C++?


According to Wiki, the big endian or small endian are two ways of storing bytes of data e.g. 32-bit integer in memory locations.

For Big Endian Representations, the Most Significant Byte (MSB) is stored at lower addresses.

Big-Endian.svg_ How to Find Out Whether a Machine is Big Endian or Little Endian in C/C++? c / c++ low level programming languages tools / utilities

Big Endian Representation in Memory

For Little Endians, it is the opposite, the MSB is stored at higher addresses.

Little-Endian.svg_ How to Find Out Whether a Machine is Big Endian or Little Endian in C/C++? c / c++ low level programming languages tools / utilities

Little Endian Representation in Memory

Test Big/Little Endian in C/C++

We can write a small tool to test Whether a Machine is Big Endian or Little Endian in C/C++. First, we declare a 16-bit integer (short int), which has the value 0x0001, then we gets its pointer and deference it. If the MSB is stored at lower address (e.g. the value that pointer points to), then it is little endian.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// https://helloacm.com/how-to-find-out-whether-a-machine-is-big-endian-or-little-endian-in-cc/
#include <stdio.h>
 
#define BIG_ENDIAN 0
#define LITTLE_ENDIAN 1
 
int TestByteOrder() {
        short int word = 0x0001;
        char *b = (char *)&word;
        return (b[0] ? LITTLE_ENDIAN : BIG_ENDIAN);
}
 
int main() {
        int r = TestByteOrder();
        printf("%s\n", r == LITTLE_ENDIAN ? "Little Endian" : "Big Endian");
        return r;
}
// https://helloacm.com/how-to-find-out-whether-a-machine-is-big-endian-or-little-endian-in-cc/
#include <stdio.h>

#define BIG_ENDIAN 0
#define LITTLE_ENDIAN 1

int TestByteOrder() {
        short int word = 0x0001;
        char *b = (char *)&word;
        return (b[0] ? LITTLE_ENDIAN : BIG_ENDIAN);
}

int main() {
        int r = TestByteOrder();
        printf("%s\n", r == LITTLE_ENDIAN ? "Little Endian" : "Big Endian");
        return r;
}

To compile it, using e.g. gcc TestByteOrder.c -o TestByteOrder:

1
2
[email protected]:~$ ./TestByteOrder
Little Endian
[email protected]:~$ ./TestByteOrder
Little Endian

Pre-compiled Binaries

Extract the zip and Run TestByteOrder in the console, what is your result? Share yours by commenting below.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
436 words
Last Post: What is R1Soft Continuous Data Protection?
Next Post: How to Find the Maximum of Two Integers without Using Comparison Operator?

The Permanent URL is: How to Find Out Whether a Machine is Big Endian or Little Endian in C/C++?

One Response

  1. Luuk

Leave a Reply