std::endian

来自cppreference.com
< cpp‎ | types
在标头 <bit> 定义
enum class endian

{
    little = /*实现定义*/,
    big    = /*实现定义*/,
    native = /*实现定义*/

};
(C++20 起)

指示所有标量类型的端序:

  • 若所有标量类型均为小端,则 std::endian::native 等于 std::endian::little
  • 若所有标量类型均为大端,则 std::endian::native 等于 std::endian::big

亦支持极端情况:

  • 若对所有标量类型进行 sizeof 运算都等于 1,则端序没有意义,且 std::endian::little, std::endian::bigstd::endian::native 三个值相同
  • 若平台使用混合端序,则 std::endian::native 既不等于 std::endian::big 亦不等于 std::endian::little

可能的实现

enum class endian
{
#ifdef _WIN32
    little = 0,
    big    = 1,
    native = little
#else
    little = __ORDER_LITTLE_ENDIAN__,
    big    = __ORDER_BIG_ENDIAN__,
    native = __BYTE_ORDER__
#endif
};

示例

#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";
}

可能的输出:

little-endian

参阅

(C++23)
反转给定整数值中的字节
(函数模板)