简体   繁体   English

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

[英]C++ How do I convert int to hex char (as in 0x0A, not "0A")

Sorry if this is hard to understand :P I'm trying to convert a decimal int value to a char value so I can write it in binary mode with fstream in c++.抱歉,如果这很难理解:P 我正在尝试将十进制 int 值转换为 char 值,以便我可以在 C++ 中使用 fstream 以二进制模式编写它。 I did this: char hexChar = 0x01; file.write(hexChar, size);我这样做了: char hexChar = 0x01; file.write(hexChar, size); char hexChar = 0x01; file.write(hexChar, size); . . That worked fine until I needed to write a decimal int from user.这工作正常,直到我需要从用户写一个十进制整数。 My question is, how do I convert decimal int to char hex value like this: int decInt = 10; char hexChar = 0x00; hexChar = decInt; file.write(hexChar, size);我的问题是,如何将十进制 int 转换为 char 十六进制值,如下所示: int decInt = 10; char hexChar = 0x00; hexChar = decInt; file.write(hexChar, size); int decInt = 10; char hexChar = 0x00; hexChar = decInt; file.write(hexChar, size); PS: I've been googling this for about an hour, and haven't found an answer. PS:我已经在谷歌上搜索了大约一个小时,还没有找到答案。 Every other solved problem with this has been decimal to ASCII hex value like "0A" using cout, not 0x0A using fstream.其他所有解决的问题都是使用 cout 将十进制转换为 ASCII 十六进制值,如“0A”,而不是使用 fstream 的 0x0A。

It doesn't matter which kind of literal you are using to initialize an int variable您使用哪种文字来初始化int变量并不重要

int x = 0x0A;
int y = 10;

The above statements assign the exactly same value to the variables.上面的语句为变量分配了完全相同的值。

To output numeric values with hexadecimal base representation you can use the std::hex I/O stream manipulator:要使用十六进制基本表示输出数值,您可以使用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;
}

Output:输出:

x = 0xa
y = 10

See the live sample here .此处查看实时示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM