簡體   English   中英

reinterpret_cast交換位?

[英]reinterpret_cast swaps bits?

當我發現它的輸出完全錯誤時,我正在測試一個簡單的編譯器。 實際上,輸出的字節序從小到大。 經過仔細檢查,令人反感的代碼原來是這樣的:

const char *bp = reinterpret_cast<const char*>(&command._instruction);
for (int i = 0; i < 4; ++i)
  out << bp[i];

四字節指令被重新解釋為一組一字節字符,並打印到標准輸出(笨拙,是的,但是這個決定不是我的)。 在我看來,為什么要交換這些位似乎並不合邏輯,因為char指針首先應指向最高有效位(在此x86系統上)。 例如,給定0x00 ... 04,char指針應指向0x00,而不是0x04。 情況是后者。

我創建了一個簡單的代碼演示:

#include <bitset>
#include <iostream>
#include <stdint.h>

int main()
{
  int32_t foo = 4;
  int8_t* cursor = reinterpret_cast<int8_t*>(&foo);

  std::cout << "Using a moving 8-bit pointer:" << std::endl;
  for (int i = 0; i < 4; ++i)
    std::cout << std::bitset<8>(cursor[i]) << " "; // <-- why?

  std::cout << std::endl << "Using original 4-byte int:" << std::endl;
  std::cout << std::bitset<32>(foo) << std::endl;

  return 0;
}

輸出:

Using a moving 8-bit pointer:
00000100 00000000 00000000 00000000
Using original 4-byte int:
00000000000000000000000000000100

在我看來,為什么要交換這些位似乎並不合邏輯,因為char指針首先應指向最高有效位(在此x86系統上)。

在x86系統上,指向多字節對象基址的指針不是指向最高有效字節,而是指向最低有效字節。 這稱為“小尾數”字節順序。

在C語言中,如果我們獲取一個占用多個字節的對象的地址,並將其轉換為char * ,則它指向該對象的基址:那個地址被認為是最低有效地址,指針可以從該地址開始正移位(使用+++等)以獲取其他字節。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM