Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/types/endian"

From cppreference.com
< cpp‎ | types
m (Example: fmt)
m (c)
Line 8: Line 8:
 
     little = /*implementation-defined*/,
 
     little = /*implementation-defined*/,
 
     big    = /*implementation-defined*/,
 
     big    = /*implementation-defined*/,
     native = /*implementation-defined*/
+
     native = /*implementation-defined*/,
 
};
 
};
 
}}
 
}}
Line 19: Line 19:
  
 
Corner case platforms are also supported:
 
Corner case platforms are also supported:
* If all scalar types have {{tt|sizeof}} equal to {{tt|1}}, endianness does not matter and all three values, {{c|std::endian::little}}, {{c|std::endian::big}}, and {{c|std::endian::native}} are the same.
+
* If all scalar types have {{tt|sizeof}} equal to {{c|1}}, endianness does not matter and all three values, {{c|std::endian::little}}, {{c|std::endian::big}}, and {{c|std::endian::native}} are the same.
 
* If the platform uses mixed endian, {{c|std::endian::native}} equals neither {{c|std::endian::big}} nor {{c|std::endian::little}}.
 
* If the platform uses mixed endian, {{c|std::endian::native}} equals neither {{c|std::endian::big}} nor {{c|std::endian::little}}.
  

Revision as of 14:25, 11 June 2023

 
 
 
Defined in header <bit>
enum class endian

{
    little = /*implementation-defined*/,
    big    = /*implementation-defined*/,
    native = /*implementation-defined*/,

};
(since C++20)

Indicates the endianness of all scalar types:

  • 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.

Corner case platforms are also supported:

  • 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.
  • If the platform uses mixed endian, std::endian::native equals neither std::endian::big nor std::endian::little.

Contents

Possible implementation

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

Notes

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

Example

#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:

little-endian

See also

(C++23)
reverses the bytes in the given integer value
(function template) [edit]