大端序,小端序,Big-endian, Little-endian

在计算机中,字节序(byte order)指的是多字节数据在存储时字节的排列顺序。主要有两种字节序:大端序(big-endian)和小端序(little-endian)。

  • 大端序(Big-endian):在大端序中,最高有效字节(Most Significant Byte,MSB)存储在最低的内存地址,而最低有效字节(Least Significant Byte,LSB)存储在最高的内存地址。
  • 小端序(Little-endian):在小端序中,最低有效字节(LSB)存储在最低的内存地址,而最高有效字节(MSB)存储在最高的内存地址。

举例来说,对于一个四字节的整数 0x12345678

  • 在大端序中,内存中的存储顺序为 12 34 56 78
  • 在小端序中,内存中的存储顺序为 78 56 34 12

下面是一个简单的 C++ 示例来演示大端序:

#include <iostream>

int main() {
    // 定义一个整数
    int num = 0x12345678;

    // 获取整数的地址
    unsigned char* ptr = reinterpret_cast<unsigned char*>(&num);

    // 打印每个字节的值及其地址
    std::cout << "Memory layout in big-endian order:" << std::endl;
    for (int i = sizeof(num) - 1; i >= 0; --i) {
        std::cout << "Byte " << i << ": " << std::hex << static_cast<int>(ptr[i]) << " (Address: " << reinterpret_cast<void*>(&ptr[i]) << ")" << std::endl;
    }

    return 0;
}

 

/**
        Memory layout in big-endian order:
        Byte 3: 12 (Address: 0x7ffc761e9bff)
        Byte 2: 34 (Address: 0x7ffc761e9bfe)
        Byte 1: 56 (Address: 0x7ffc761e9bfd)
        Byte 0: 78 (Address: 0x7ffc761e9bfc)
*/

 

在这个示例中,我们首先定义了一个整数 num,然后通过指针将其转换为字节序列。然后,我们逆序遍历字节序列,并打印出每个字节的值及其地址。由于我们的系统是大端序,因此打印结果会按照大端序的顺序显示每个字节的值及其地址。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章