Files
CPlusPlusThings/site_extras/modern-cpp-cpp20-cpp20-endian.md
light-city dfe1c933b3 docs: address community issue feedback (#5 #338 #142 #246 #136 #303)
- const README: rewrite the space-saving claim per issue #5 follow-ups
  (constant-expression const vs #define immediates; which const qualify
  as constant expressions)
- const README: fix the class-section diagnosis per issue #338 (overload
  resolution picks the const overload; the restriction only surfaces
  once that overload is removed)
- sizeof README: virtual-inheritance result is compiler-dependent
  (GCC merges vbptr+vfptr -> 16, MSVC keeps them separate -> 32) #246
- static README: new section on internal linkage / access restriction
  with anonymous-namespace comparison #142
- 10-day practice: full problem list table + fixed day links #136
- new design_pattern/singleton/singleton_default.hpp: reusable
  thread-safe CRTP singleton template, compile+concurrency tested #303
2026-10-13 19:23:54 +08:00

70 lines
2.0 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp20/cpp20-endian/) 的文章,由站点同步脚本导出。
# C++20 字节序 endian
在面试的时候,字节序通常是一个非常重要的考点,会考察:
- 大小端概念
- 如何判断大小端
- 主机字节序
- 网络字节序
- 等等
,那么判别方式其实有很多种,例如:
- C++20的endian
- union
- 地址转换
- htons
那么本节就来阐述一下C++20的大小端使用与基础知识。
**注:懒人版,4种方式判别大小端源码已放星球,感兴趣获取即可。**
## 1.字节序基础
系统的字节序指的是字节在内存中存储或通过网络传输的顺序。大端系统在最低内存地址存储最高有效字节(MSB)。这在各种网络协议中用于通过网络发送数据,也称为网络字节序。在小端系统中,最低有效字节(LSB)存储在最低内存地址。例如,十六进制数0x12345678的存储方式如下:
- 大端:
```
地址 | 值
n | 0x12
n + 1 | 0x34
n + 2 | 0x56
n + 3 | 0x78
```
- 小端
```
地址 | 值
n | 0x78
n + 1 | 0x56
n + 2 | 0x34
n + 3 | 0x12
```
根据架构的不同,不同的系统可能是大端或小端的主机字节序。
## 2.字节序的重要性
那么,这为什么重要呢?如果你需要通过网络发送数据,那么你需要确保它以网络字节序传输。在大多数情况下,你的主机字节序将是小端,这意味着你需要在传输数据之前反转字节的顺序。
## 3.检查字节序
C++20引入了一种更简单且更可移植的方式来检查字节序,即std::endian。你可以使用std::endian::native检查系统的主机字节序。下面是一个简单的例子:
```cpp
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;
}
}
```