簡體   English   中英

C ++ cout十六進制格式

[英]C++ cout hex format

我是ac編碼器,是c ++的新手。

我嘗試用奇怪的輸出cout打印以下內容。 對此行為的任何評論表示贊賞。

#include<iostream>
using namespace std;

int main()
{
        unsigned char x = 0xff;

        cout << "Value of x  " << hex<<x<<"  hexadecimal"<<endl;

        printf(" Value of x %x by printf", x);
}

輸出:

 Value of x  ÿ  hexadecimal
 Value of x ff by printf

<< char作為要輸出的'字符'處理,並且只輸出該字節。 hex僅適用於類似整數的類型,因此以下將執行您期望的操作:

cout << "Value of x  " << hex << int(x) << "  hexadecimal" << endl;

Billy ONeal對static_cast的建議如下:

cout << "Value of x  " << hex << static_cast<int>(x) << "  hexadecimal" << endl;

您正在正確執行十六進制部分,但x是一個字符,C ++正在嘗試將其作為字符打印。 你必須把它強制轉換為整數。

#include<iostream>
using namespace std;

int main()
{
        unsigned char x = 0xff;

        cout << "Value of x  " << hex<<static_cast<int>(x)<<"  hexadecimal"<<endl;

        printf(" Value of x %x by printf", x);
}

如果我正確理解你的問題,你應該知道如何將hex轉換為dec因為你已經分配了unsigned char x = 0xff;

#include <iostream>
int main()
{
    unsigned char x = 0xff;
    std::cout << std::dec << static_cast<int>(x) << std::endl;
}

它應該給出值255

有關str流到dec更多詳細信息,請參閱http://www.cplusplus.com/reference/ios/dec/

如果你想知道十進制值的十六進制值,這是一個簡單的例子

#include <iostream>
#include <iomanip>

int main()
{
    int x = 255;

    std::cout << std::showbase << std::setw(4) << std::hex << x << std::endl;
}

打印oxff

如果你想在ff之前看到0x ,那么庫<iomanip>是可選的。 hex數字打印相關的原始回復位於http://www.cplusplus.com/forum/windows/51591/

暫無
暫無

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

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