在計算機中,字節序(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
,然後通過指針將其轉換爲字節序列。然後,我們逆序遍歷字節序列,並打印出每個字節的值及其地址。由於我們的系統是大端序,因此打印結果會按照大端序的順序顯示每個字節的值及其地址。