首页 文章

C如何将int转换为十六进制char(如0x0A,而不是“0A”)

提问于
浏览
2

很抱歉,如果这很难理解:P我正在尝试将十进制int值转换为char值,因此我可以在c中使用fstream以二进制模式编写它 . 我这样做了: char hexChar = 0x01; file.write(hexChar, size); . 这工作正常,直到我需要从用户写一个十进制int . 我的问题是,如何将十进制int转换为char十六进制值,如下所示: int decInt = 10; char hexChar = 0x00; hexChar = decInt; file.write(hexChar, size); PS:我've been googling this for about an hour, and haven' t找到了答案 . 所有其他解决的问题都是十进制到ASCII十六进制值,如"0A"使用cout,而不是0x0A使用fstream .

1 回答

  • 2

    使用哪种文字来初始化 int 变量并不重要

    int x = 0x0A;
    int y = 10;
    

    上述语句为变量赋予完全相同的值 .

    要使用十六进制基表示输出数值,可以使用std::hex I / O流操纵器:

    #include <iostream>
    #include <iomanip>
    
    
    int main() {
        int x = 10; // equivalents to 0x0A
        int y = 0x0A; // equivalents to 10
    
        std::cout << std::setw(2) << std::setfill('0') 
                  << "x = " << std::hex <<  "0x" << x << std::endl;
        std::cout << "y = " << std::dec << y << std::endl;
    
        return 0;
    }
    

    输出:

    x = 0xa
    y = 10
    

    查看实时样本here .

相关问题