Little Endian, Big Endian, 网络字节序

    xiaoxiao2025-11-04  7

    字节序是指多字节数据在计算机内存中存储或者网络传输时各字节的存储顺序。 Little Endian还是Big Endian与操作系统和芯片类型都有关系。 Motorola的PowerPC系列CPU和Intel的x86系列CPU; PowerPC系列采用big endian方式存储数据,而x86系列则采用little endian方式存储数据。 (1)Little endian: 将低字节存储在起始地址 0x12345678 on a little-endian system Memory offset    0    1    2    3 Memory content    0x78    0x56    0x34    0x12 (2)Big endian: 将高字节存储在起始地址 0x12345678 on a big-endian system Memory offset    0    1    2    3 Memory content    0x12    0x34    0x56    0x78 (3)Big endian vs. little endian #include <stdio.h> int main () {     int i = 0x12345678;     if (*(char *)&i == 0x12)         printf ("Big endian\n");     else if (*(char *)&i == 0x78)         printf ("Little endian\n");     return 0; } (4)网络字节序是TCP/IP中规定好的一种数据表示格式,它与具体的CPU类型、操作系统等无关, 从而可以保证数据在不同主机(不同程序)之间传输时能够被正确解释。 在IPV4,IPV6,TCP,UDP数据包中广泛采用Big endian数据格式化数据,所以Big endian又被称为网络字节序。 /* Change endianness for byte swap in an unsigned 32-bit integer */ uint32_t ChangeEndianness(uint32_t value) {     uint32_t result = 0;     result |= (value & 0x000000FF) << 24;     result |= (value & 0x0000FF00) << 8;     result |= (value & 0x00FF0000) >> 8;     result |= (value & 0xFF000000) >> 24;     return result; } 参考: http://www.ibm.com/developerworks/library/l-port64/
    转载请注明原文地址: https://ju.6miu.com/read-1303833.html
    最新回复(0)