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

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

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

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

    In Rust (byteorder crate required):

    use std::any::TypeId;
    
    let is_little_endian = TypeId::of::<byteorder::NativeEndian>() == TypeId::of::<byteorder::LittleEndian>();
    
    0 讨论(0)
  • 2020-11-28 21:12

    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";
    }
    
    0 讨论(0)
  • 2020-11-28 21:13

    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 */
    
    0 讨论(0)
  • 2020-11-28 21:14

    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";
    }
    
    0 讨论(0)
  • 2020-11-28 21:17

    In Nim,

    echo cpuEndian
    

    It is exported from the system module.

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

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

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