15

Possible Duplicate:
Detecting endianness programmatically in a C++ program

Is there any library function available to find the endian-ness of my PC?

Community
  • 1
  • 1
Dinesh
  • 16,014
  • 23
  • 80
  • 122

4 Answers4

59

Why you need a library if you can find it like this? :)

int num = 1;

if (*(char *)&num == 1)
{
    printf("Little-Endian\n");
}
else
{
    printf("Big-Endian\n");
}
Artur
  • 7,038
  • 2
  • 25
  • 39
COD3BOY
  • 11,964
  • 1
  • 38
  • 56
  • maybe explain why this works like @Eric J. does below – bjackfly Aug 09 '13 at 04:00
  • 13
    int num=1 will stored as 000.0001 or 100.000 depending on endianness. (char*)&num will be pointing to first byte of that int. now if that byte reads 1, then its little endian otherwise big endian. – hasanatkazmi Apr 17 '14 at 02:25
  • 1
    @hasanatkazmi How do you know if the computer will store the number in 2 bytes or 4 bytes? Also, why are you using 7 bits anyway? – Koray Tugay Jan 20 '16 at 18:33
  • 1
    @hasanatkazmi: Looks like you mix endianess with bit ordering within a byte (for example motorola docs show bit order the opposite way contrary to the rest of the world) – Artur Feb 28 '16 at 17:42
6

I'm not aware of a library function.

You can get the address of an integer, then treat that address as a character pointer and write data into the bytes that comprise the integer. Then, read out what is actually in the integer and see if you get a result consistent with a big endian or little endian architecture.

Eric J.
  • 147,927
  • 63
  • 340
  • 553
6

use this code:

union 
{
    uint8  c[4];
    uint32 i;
} u;

u.i = 0x01020304;

if (0x04 == u.c[0])
    printf("Little endian\n");
else if (0x01 == u.c[0])
    printf("Big endian\n");
Kamyar Souri
  • 1,871
  • 19
  • 29
  • You do not need "else if" - "else" is enough since if it is not little endianess it is big endianess. – Artur Feb 28 '16 at 17:37
  • 3
    @Artur: ha ha ha ha! There are other alternatives: PDP11 used 16-bit words in big-endian order ... with the bytes in the word in little-endian order (it might have been visa-versa - it was a while ago now). – Martin Bonner supports Monica Sep 27 '16 at 10:39
3

There isn't a standard function to do so (as in C standard, or POSIX standard).

If your PC is a (Windows-style) PC running Intel, it is little-endian.

If you wish to find the byte-order on your machine, you can use the not wholly defined behaviour (but it usually works - I've not heard of anywhere that it doesn't work) of this technique:

enum { BigEndian, LittleEndian };

int endianness(void)
{
    union
    {
        int  i;
        char b[sizeof(int)];
    } u;
    u.i = 0x01020304;
    return (u.b[0] == 0x01) ? BigEndian : LittleEndian;
}

This code does assume a 32-bit int type (rather than 64-bit or 16-bit).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278