Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine endianness at compile-time?

Tags:

c++

How can I determine at compile time if my platform is little endian or big endian? I have seen many ways to determine at runtime using casting, and some platform-dependent options. Is there a portable or standard way to do this?

constexpr bool is_little_endian = ?;
like image 965
Ryan Haining Avatar asked May 02 '18 23:05

Ryan Haining


1 Answers

C++20 added std::endian to <bit>* which can be used in a constexpr context.

Live example of below code:

if constexpr (std::endian::native == std::endian::little) {
    std::cout << "litle endian\n";
} else if constexpr(std::endian::native == std::endian::big) {
    std::cout << "big endian\n";
} else {
    std::cout << "something silly\n";
}

* It was originally <type_traits> and will be there in older implementations.

like image 108
Ryan Haining Avatar answered Nov 10 '22 09:11

Ryan Haining