# std::endian

< cpp‎ | types

定义于头文件 `<bit>` |  |
enum class endian { little = /*implementation-defined*/, big = /*implementation-defined*/, native = /*implementation-defined*/ }; |  | (C++20 起)

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

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

亦支持极端情况：

- 若所有标量类型拥有等于 1 的 sizeof ，则端序无影响，且 `std::endian::little`, `std::endian::big` 及 `std::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

### 参阅

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