How can I find Endian-ness of my PC programmatically using C? [duplicate]

浪子不回头ぞ 提交于 2019-11-28 18:53:31
COD3BOY

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");
}

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.

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");

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).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!