This article will show you how to write a c program to check endianness.
What is Endianness?
Endianness is the order by which bytes are stored in computer memory. Endianness (Her Royal Highness) tells us whether bytes are represented from left to right or right to left.
How does Endianness work?
There are two ways Her Royal Highness allows data to be stored in memory:
- Little-Endian: Store the least significant byte in the smallest address
- Big-Endian: Store the most significant byte in the smallest address
Why check for Endianness?
Suppose we store integer values in a file and send the file to a machine with opposite endianness, it causes us to read the reversed values of our integers and this can be a problem.
How to check for endianness in C?
We already know that in little endian machine, the least significant byte of any multibyte data is stored at the lowest memory address. So in the below program, we are asking her royal highness to let us know the value of the lowest address in memory. If the value is 1 then she will print little endian otherwise, big endian will be printed.
#include <stdio.h>
/**
* main - checks the endianness
*
* Return: Success (0)
*/
int main(void)
{
unsigned int i = 1;
char *c;
c = (char *) &i; /* points to the first byte of the integer i */
if (*c == 1) /* 1st byte looks like 0x01 */
{
printf("Little Endian\n");
}
else /* 1st byte looks like 0x00 */
{
printf("Big Endian\n");
}
return (0);
}
Output
Little Endian
Code Explanation
If your machine is little endian, the data in the memory will be something like the expression below:
On the contrary, if your machine is big endian, it will look like the expression below:
Conclusion
There is no meaning to say which endian is better, there is no advantage of using one endianness over the other as both only define the byte sequence order. Most desktop and personal computers today have little-endian architecture.
I would like to know your thoughts on Her Royal Highness 😃. Please remember to leave a comment in the comment box and hit the follow button.
Top comments (0)