Is there a programmatic way to detect whether or not you are on a big-endian or little-endian architecture? I need to be able to write code that will execute on an Intel or PPC system and use exactly the same code (i.e. no conditional compilation).
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- What are the problems associated to Best First Sea
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
untested, but in my mind, this should work? cause it'll be 0x01 on little endian, and 0x00 on big endian?
Please see this article:
You can also do this via the preprocessor using something like boost header file which can be found boost endian
Do not use a
union
!C++ does not permit type punning via
union
s!Reading from a union field that was not the last field written to is undefined behaviour!
Many compilers support doing so as an extensions, but the language makes no guarantee.
See this answer for more details:
https://stackoverflow.com/a/11996970
There are only two valid answers that are guaranteed to be portable.
The first answer, if you have access to a system that supports C++20,
is to use
std::endian
from the<type_traits>
header.(At the time of writing, C++20 has not yet been released, but unless something happens to affect
std::endian
's inclusion, this shall be the preferred way to test the endianness at compile time from C++20 onwards.)C++20 Onwards
Prior to C++20, the only valid answer is to store an integer and then inspect its first byte through type punning.
Unlike the use of
union
s, this is expressly allowed by C++'s type system.It's also important to remember that for optimum portability
static_cast
should be used,because
reinterpret_cast
is implementation defined.C++11 Onwards
C++11 Onwards (without enum)
C++98/C++03
Declare an int variable:
Now use char* pointers to various parts of it and check what is in those parts.
Depending on which one points to 0xFF byte now you can detect endianness. This requires sizeof( int ) > sizeof( char ), but it's definitely true for the discussed platforms.
I would do something like this:
Along these lines, you would get a time efficient function that only does the calculation once.