Last updated:2026-10-12
C++20 Byte Order (endian)¶
In interviews, byte order is usually a very important topic. Interviewers will check:
- The concepts of big-endian and little-endian
- How to detect big-endian vs little-endian
- Host byte order
- Network byte order
- And so on
There are actually many ways to detect it, for example:
- C++20's endian
- union
- Address casting
- htons
So this section covers the usage of and the fundamentals behind big-endian/little-endian in C++20.
Note: for the lazy version, the source code detecting endianness in 4 ways has been put in the Knowledge Planet — grab it there if you are interested.
1. Byte-Order Basics¶
A system's byte order refers to the order in which bytes are stored in memory or transmitted over a network. Big-endian systems store the most significant byte (MSB) at the lowest memory address. This is what various network protocols use to send data over the network, and it is also called network byte order. In little-endian systems, the least significant byte (LSB) is stored at the lowest memory address. For example, the hexadecimal number 0x12345678 is stored as follows:
- Big-endian:
- Little-endian
Depending on the architecture, different systems may have either big-endian or little-endian host byte order.
2. Why Byte Order Matters¶
So why does this matter? If you need to send data over a network, you must make sure it is transmitted in network byte order. In most cases your host byte order will be little-endian, which means you need to reverse the order of the bytes before transmitting the data.
3. Checking Byte Order¶
C++20 introduced a simpler and more portable way to check the byte order: std::endian. You can use std::endian::native to check the system's host byte order. Here is a simple example:
void checkEndianness() {
if constexpr (std::endian::native == std::endian::little) {
std::cout << "小端" << std::endl;
} else if constexpr (std::endian::native == std::endian::big) {
std::cout << "大端" << std::endl;
} else {
std::cout << "未知" << std::endl;
}
}
Related Topics¶
- Getting Started with C++20 Coroutines | C++那些事
- C++20 channel in Practice | C++那些事
- C++20 Concepts | C++那些事
- C++20 constexpr and the Comma Expression | C++那些事
- C++20 Lambda Expressions (Part 1) | C++那些事
- C++20 Modules | C++那些事
- C++20 Ranges Library | C++那些事
- C++20 std::span Design and Pitfalls | C++那些事
- A Guide to C++20 New Features | C++那些事
- C++20 [[likely]] and [[unlikely]] | C++那些事