How to check whether a system is big endian or little endian?

谁说我不能喝 提交于 2019-11-27 03:00:52
belwood

In C, C++

int n = 1;
// little endian if true
if(*(char *)&n == 1) {...}

See also: Perl version

In Python:

from sys import byteorder
print(byteorder)
# will print 'little' if little endian

Another C code using union

union {
    int i;
    char c[sizeof(int)];
} x;
x.i = 1;
if(x.c[0] == 1)
    printf("little-endian\n");
else    printf("big-endian\n");

It is same logic that belwood used.

If you are using .NET: Check the value of BitConverter.IsLittleEndian.

A one-liner with Perl (which should be installed by default on almost all systems):

perl -e 'use Config; print $Config{byteorder}'

If the output starts with a 1 (least-significant byte), it's a little-endian system. If the output starts with a higher digit (most-significant byte), it's a big-endian system. See documentation of the Config module.

Galik

A C++ solution:

namespace sys {

const unsigned one = 1U;

inline bool little_endian()
{
    return reinterpret_cast<const char*>(&one) + sizeof(unsigned) - 1;
}

inline bool big_endian()
{
    return !little_endian();
}

} // sys

int main()
{
    if(sys::little_endian())
        std::cout << "little";
}
Rigel Hsu

In Linux,

static union { char c[4]; unsigned long mylong; } endian_test = { { 'l', '?', '?', 'b' } };
#define ENDIANNESS ((char)endian_test.mylong)

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