[英]C++ sign extension
我正在處理一個家庭作業問題,從二進制文件打印。 我搜索並發現我的問題是一個符號擴展問題。
在c中,正確的操作是轉換為(unsigned char)
我試過這個解決方案,它不適用於cout
帶(unsigned)的輸出是:
4D 5A FFFFFF90 00 03 00 00 00 04 00 00 00 FFFFFFFF FFFFFFFF 00 00
帶(unsigned char)的輸出是:
0M 0Z 0ê 0� 0 0� 0� 0� 0 0� 0� 0� 0ˇ 0ˇ 0� 0�
任何指導都是最有幫助的;
這是代碼:
void ListHex(ifstream &inFile)
{
// declare variables
char buf[NUMCHAR];
unsigned char bchar;
while(!inFile.eof())
{
inFile.read(buf,NUMCHAR);
for (int count = 0; count < inFile.gcount(); ++count)
{
cout << setfill('0') << setw(2) << uppercase << hex <<
(unsigned)buf[count] << ' ';
}
cout << '\n';
}
}
怎么樣cout <<setfill('0') << setw(2) << uppercase << hex << (0xFF & buf[count])
void ListHex(std::istream& inFile) {
// declare variables
char c;
while(inFile >> c) {
std::cout << std::setw(2) << std::hex
<< static_cast<int>(c);
}
}
我建議按字符執行此字符,原因是存在各種各樣的字節序問題,我甚至不想在處理rinterpretive int轉換時。 std::ifstream
無論如何都會為你緩沖字符(你的操作系統也可能也是如此)。
請注意我們如何將文件流作為更通用的std::istream
這允許我們傳入任何類型的istream
包括std::istringstream
, std::cin
和std::ifstream
。
例如:
ListHex(std::cin);
std::istringstream iss("hello world!");
ListHex(iss);
會使用戶輸入十六進制。
使用緩沖區
void ListHex(std::istream& inFile) {
// declare variables
char arr[NUMCHAR];
while(inFile.read(arr, NUMCHAR)) {
for(std::size_t i=0; i!=NUMCHAR; ++i) {
std::cout << std::setw(2) << std::hex
<< static_cast<int>(arr[i]);
}
}
}
您可以通過屏蔽高位來擺脫符號擴展:
(((unsigned) buf[count)) & 0xff)
std :: cout將unsigned char打印為字符,而不是整數。 你可以在這里進行兩次演員表演 - 有些內容如下:
static_cast <int> (static_cast <unsigned char> (buf[count]))
或者,使用unsigned char緩沖區和單個強制轉換:
void ListHext(ifstream& inFile)
{
unsigned char buf[NUMCHAR];
while (inFile.read(reinterpret_cast <char*> (&buf[0]), NUMCHAR))
{
for (int i=0; i < NUMCHAR; ++i)
cout << ... << static_cast <int> (buf[i]) << ' ';
cout << endl;
}
}
編輯:此處不應使用蒙版,因為它假設特定的字符大小。 僅當CHAR_BIT為8時,以下內容才相同:
// bad examples
x & 0xFF // note - implicit int conversion
static_cast <int> (x) & 0xFF // note - explicit int conversion
// good example
static_cast <int> (static_cast <unsigned char> (x))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.