字节序: big-endian vs little-endian

如何快速记忆

big-endian又名大尾序,就是数值的尾巴存储在大地址上。尾是相对我们认识的变量值,大是指地址;
相对应,little-endian又名小尾序,数值的尾巴存储在小地址上。
一句话大小是尾巴的地址,尾巴是数值的尾巴,指的是0xABCD(十进制43981)的D
字节序: big-endian vs little-endian_第1张图片 字节序: big-endian vs little-endian_第2张图片

如何判断字节序是大端还是小端

  1. 通过二进制工具查看: readelf -h main
int main(){
	return 0;
}

编译出二进制

g++ main.cpp -o main

使用readelf查看字节序

readelf -h main

结果如下(ELF Magic第6个字节代表字节序,0 无效格式; 1 小端格式; 2 大端格式)
ELF Header:
Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
Class: ELF64
Data: 2’s complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: DYN (Shared object file)
Machine: Advanced Micro Devices X86-64
Version: 0x1
Entry point address: 0x1060
Start of program headers: 64 (bytes into file)
Start of section headers: 14976 (bytes into file)
Flags: 0x0
Size of this header: 64 (bytes)
Size of program headers: 56 (bytes)
Number of program headers: 14
Size of section headers: 64 (bytes)
Number of section headers: 32
Section header string table index: 31

  1. 使用命令行查看: lscpu | grep -i byte

yms@yms-System-Product-Name:~/ws/thread_local$ lscpu | grep -i byte
Byte Order: Little Endian

  1. 使用代码(union)进行判断
 #include 
 
 union Endian {
     char a;
     int b;
 };
 
 int main(){
     Endian endian;
     endian.b = 1;
 
     if (endian.a == 1) {
         printf("little endian\n");
     }else{
         printf("big endian\n");
     }   
     return 0;
 }

yms@yms-System-Product-Name:~/ws$ ./main
little endian

网络序

网络传输一般采用大端序,也被称之为网络字节序,或网络序。IP协议中定义大端序为网络字节序。

你可能感兴趣的:(Linux,字节序,大端小端)