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

后端 未结 12 860
时光说笑
时光说笑 2020-11-28 20:25

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

相关标签:
12条回答
  • 2020-11-28 21:20

    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.

    0 讨论(0)
  • 2020-11-28 21:21

    In Python:

    from sys import byteorder
    print(byteorder)
    # will print 'little' if little endian
    
    0 讨论(0)
  • 2020-11-28 21:25

    Using Macro,

    const int isBigEnd=1;
    #define is_bigendian() ((*(char*)&isBigEnd) == 0)
    
    0 讨论(0)
  • 2020-11-28 21:27

    In C, C++

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

    See also: Perl version

    0 讨论(0)
  • 2020-11-28 21:28

    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.

    0 讨论(0)
  • 2020-11-28 21:31

    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.

    0 讨论(0)
提交回复
热议问题