std::endian(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– std::endian πŸ’–

okay so bestie, this one comes to you from the C++ Standard Library and it's genuinely one of the cutest little enums you'll ever meet β€” no cap. Let's get into it πŸŽ€


✨ NAME ✨

std::endian β€” literally just std::endian, she's an enum class and she knows it πŸ‘‘


🌸 Synopsis 🌸

She lives in the <bit> header, queen of the bit ops neighborhood:

Defined in header <bit>
enum class endian

{
    little = /*implementation-defined*/,  (since C++20)
    big    = /*implementation-defined*/,
    native = /*implementation-defined*/,

};

So what does she do? She indicates the endianness of all scalar types πŸ¦‹ and the rules are:

  • If all scalar types are little-endian, std::endian::native equals std::endian::little. πŸ’…
  • If all scalar types are big-endian, std::endian::native equals std::endian::big. πŸ’…

And yes, the corner-case platforms get love too, we don't leave anyone out:

  • If all scalar types have sizeof equal to 1, endianness does not matter and all three values, std::endian::little, std::endian::big, and std::endian::native are the same. 🫢 (when byte order is simply not the vibe)
  • If the platform uses mixed endian, std::endian::native equals neither std::endian::big nor std::endian::little. 😭 chaotic but valid

🧚 Possible implementation 🧚

here's what she looks like if you had to write her yourself, iykyk:

enum class endian
{
#if defined(_MSC_VER) && !defined(__clang__)
    little = 0,
    big    = 1,
    native = little
#else
    little = __ORDER_LITTLE_ENDIAN__,
    big    = __ORDER_BIG_ENDIAN__,
    native = __BYTE_ORDER__
#endif
};

look at those preprocessor macros, iconic honestly 🌈


⭐ Notes ⭐

feature-test macro moment, we love a paper trail:

  • Feature-test macro: __cpp_lib_endian
  • Value: 201907L
  • Std: (C++20)
  • Feature: std::endian

πŸ”₯ Example πŸ”₯

run this code bestie, go go go:

#include <bit>
#include <iostream>

int main()
{
    if constexpr (std::endian::native == std::endian::big)
        std::cout << "big-endian\n";
    else if constexpr (std::endian::native == std::endian::little)
        std::cout << "little-endian\n";
    else
        std::cout << "mixed-endian\n";
}

Possible output:

mixed-endian

πŸ’€ when your platform just has to be different


πŸ‘‘ See also πŸ‘‘

  • byteswap β€” reverses the bytes in the given integer value, (C++23) (function template) β€” she's the little sibling and she ate 🌟

okay that's the whole page, mwah πŸ’‹ this was pulled from http://cppreference.com, dated 2024.06.10, and it's page std::endian(3) β€” go forth and check your byte order bestie, ily, bye πŸŽ€πŸ’–βœ¨

πŸ“¦ where this page comes from