Ryan Haining
Ryan Haining

Reputation: 36792

How to determine endianness at compile-time?

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 = ?;

Upvotes: 10

Views: 2153

Answers (1)

Ryan Haining
Ryan Haining

Reputation: 36792

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.

Upvotes: 16

Related Questions