9

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 = ?;
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
  • This question was marked as a duplicate of https://stackoverflow.com/questions/4239993/determining-endianness-at-compile-time, but that question is for C not C++. – Mark Ransom May 02 '18 at 23:12
  • 2
    Possible duplicate of [Detecting endianness programmatically in a C++ program](https://stackoverflow.com/questions/1001307/detecting-endianness-programmatically-in-a-c-program) – Justin May 02 '18 at 23:19
  • 1
    Note that the solution presented here is the same as one in my proposed dup: https://stackoverflow.com/a/38141476/1896169 – Justin May 02 '18 at 23:23
  • my guess is that you want to know the endianness _so that_ ...? Most things that depend on byte order really want to translate from one to the other. This is exactly what the [htonl](https://stackoverflow.com/questions/30386769/when-and-how-to-use-c-htonl-function) and related functions are for. I'm not discounting the question for other valid cases, but don't reinvent the wheel if you don't need to! – jwm May 02 '18 at 23:24
  • 1
    @Justin there is [an answer there that uses std::endian](https://stackoverflow.com/a/38141476/1013719), but the question doesn't specifically ask for a compile-time solution, it seems lost in the noise. The question itself isn't a duplicate, does it become a duplicate when someone provides that answer? – Ryan Haining May 02 '18 at 23:26
  • @RyanHaining I'm never actually sure TBH. In this case, I believe this is a good duplicate, because many of the answers over there give compile-time solutions, as the desire for compile-time endianness detection is such a natural extension of the question – Justin May 02 '18 at 23:38
  • @Justin are there other portable compile-time solutions? The only other I see uses a union illegally. I'd be very interested if another one exists. – Ryan Haining May 02 '18 at 23:41
  • @RyanHaining Best alternative I know of is Boost: https://stackoverflow.com/a/32513998/1896169 . I can't remember the exact Boost header or the macro it defines – Justin May 02 '18 at 23:43

1 Answers1

15

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.

Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
  • 1
    `!= little` does not strictly imply big-endian. There are some less common strange byte orders out there. – aschepler May 02 '18 at 23:23