std::endian(3)
π 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::nativeequalsstd::endian::little. π - If all scalar types are big-endian,
std::endian::nativeequalsstd::endian::big. π
And yes, the corner-case platforms get love too, we don't leave anyone out:
- If all scalar types have
sizeofequal to 1, endianness does not matter and all three values,std::endian::little,std::endian::big, andstd::endian::nativeare the same. π«Ά (when byte order is simply not the vibe) - If the platform uses mixed endian,
std::endian::nativeequals neitherstd::endian::bignorstd::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
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms