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

徘徊边缘 提交于 2019-12-29 03:29:08

问题


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

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


回答1:


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



回答2:


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.




回答3:


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



回答4:


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



来源:https://stackoverflow.com/questions/8571089/how-can-i-find-endian-ness-of-my-pc-programmatically-using-c

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