# 大端和小端小记

By [itherunder](https://paragraph.com/@itherunder) · 2021-12-10

---

肾么是大小端？
-------

![image](https://storage.googleapis.com/papyrus_images/b4b12cf5b289f487542dae7937aab7e6401e1d9a6951c8f9270cefdceda3cf11.png)

image

各有什么优势？
-------

众所周知，正负号存在数字中的高位，所以大端第一个字节存的就是最高的数字字节，对于**判断正负**来说，大端更适合，同时，**网络字节序采用的是大端存储**；而对于小端来说，无论是1个字节、2个字节、4个字节，这些数字其实都是一样的，这在做**类型转换**时十分方便，同时，做算术运算时将每个字节拿出来运算直到高位，并且最终刷新符号位，这样**运算会更加高效**

怎么写一个程序判断主机字节序？
---------------

    void testendian() {
        int a = 0x12345678;
        // 1. 直接指针
        char* p = (char*)&a;
        if (*p == 0x78)
            cout << "little endian" << endl;
        else
            cout << "big endian" << endl;
    
        // 用一下联合体
        union Un {
            char c;
            int i;
        };
    
        Un un;
        un.i = 0x12345678;
        if (un.c == 0x78)
            cout << "little endian" << endl;
        else
            cout << "big endian" << endl;
    }
    

引用
--

[大小端字节序存在的意义，为什么不用一个标准呢？](https://www.zhihu.com/question/25311159) [“字节序”是个什么鬼？](https://zhuanlan.zhihu.com/p/21388517) [C语言判断大小端模式](https://blog.csdn.net/fuxingwe/article/details/8736262)

---

*Originally published on [itherunder](https://paragraph.com/@itherunder/FZePSQNwe57poHBSVtFq)*
