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

青春壹個敷衍的年華 提交于 2019-11-26 09:18:31

问题


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


回答1:


In C, C++

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

See also: Perl version




回答2:


In Python:

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



回答3:


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.




回答4:


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




回答5:


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.




回答6:


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



回答7:


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 */



回答8:


Using Macro,

const int isBigEnd=1;
#define is_bigendian() ((*(char*)&isBigEnd) == 0)



回答9:


In C

#include <stdio.h> 

/* function to show bytes in memory, from location start to start+n*/
void show_mem_rep(char *start, int n) 
 { 
      int i; 
      for (i = 0; i < n; i++) 
      printf("%2x ", start[i]); 
      printf("\n"); 
 } 

/*Main function to call above function for 0x01234567*/
int main() 
{ 
   int i = 0x01234567; 
   show_mem_rep((char *)&i, sizeof(i));  
   return 0; 
} 

When above program is run on little endian machine, gives “67 45 23 01” as output , while if it is run on big endian machine, gives “01 23 45 67” as output.




回答10:


In C++20 use std::endian:

#include <bit>
#include <iostream>

int main() {
    if constexpr (std::endian::native == std::endian::little)
        std::cout << "little-endian";
    else if constexpr (std::endian::native == std::endian::big)
        std::cout << "big-endian";
    else
        std::cout << "mixed-endian";
}


来源:https://stackoverflow.com/questions/4181951/how-to-check-whether-a-system-is-big-endian-or-little-endian

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