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.
For Little Endians, it is the opposite, the MSB is stored at higher addresses.
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
- Linux 32-bit (3kb) : gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
- Windows 32-bit (4kb) : CodeBlocks gcc 4.9.2
Extract the zip and Run TestByteOrder in the console, what is your result? Share yours by commenting below.
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: What is R1Soft Continuous Data Protection?
Next Post: How to Find the Maximum of Two Integers without Using Comparison Operator?
Running the program in C++ on an intel Windows machine gives Little Endian. R.I.P. my byte-reading program 😛