2

I'm working on a project where the endianness of the data in RAM is important. If it is big endian, I need to convert it to Little Endian. Will this short program I wrote reliably determine the endianness of any Linux system?

Also, what determines the endianness of data stored in RAM?

#include <stdio.h>
#include <stdint.h>

int main ()
{
    // This program will determine the endianness
    // of your system and print the result in human
    // readable form to stdout

    uint16_t n;
    uint8_t  *p;

    n = 0x01;
    p = (uint8_t *) &n;

    if (p[0]) {
        printf("Little Endian\n");
    } else {
        printf("Big Endian\n");
    }

    return 0;
}
dbush
  • 205,898
  • 23
  • 218
  • 273
afdggfh
  • 135
  • 9

1 Answers1

2

Don't reinvent the wheel. Use the POSIX byteorder functions.

Name
htonl, htons, ntohl, ntohs - convert values between host and network byte order

Synopsis

#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

Description

The htonl() function converts the unsigned integer hostlong from host byte order to network byte order.

The htons() function converts the unsigned short integer hostshort from host byte order to network byte order.

The ntohl() function converts the unsigned integer netlong from network byte order to host byte order.

The ntohs() function converts the unsigned short integer netshort from network byte order to host byte order.

On the i386 the host byte order is Least Significant Byte first, whereas the network byte order, as used on the Internet, is Most Significant Byte first.

To check if the system endianness you can do:

if (htonl(1) == 1) {
    // big endian
}
else {
    // little endian
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • you can also use htobe32, htole32, ... functions, as work for linux system and not network only and can detect your host endianness and convert to be/le. – AVM Jun 24 '18 at 06:21