Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/types/endian"

From cppreference.com
< cpp‎ | types
m (Correlative conjunction neither...nor: s/does not equal either/equals neither)
Line 39: Line 39:
  
 
===Example===
 
===Example===
<!--
+
{{source|1=
if (std::endian::native == std::endian::big)
+
#include <bit>
    // handle big endian
+
#include <iostream>
else if (std::endian::native == std::endian::little)
+
 
    // handle big endian
+
int main() {
else
+
 
     // handle mixed endian
+
    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';
 +
     }
 +
 
 +
}
 +
}}
 
{{example}}
 
{{example}}
  
 
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}
 
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}

Revision as of 13:57, 25 November 2020

 
 
 
Defined in header <bit>
enum class endian

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

};
(1) (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.

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

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';
    }
 
}