Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何从十六进制转换为int和char?_C++_Io - Fatal编程技术网

C++ 如何从十六进制转换为int和char?

C++ 如何从十六进制转换为int和char?,c++,io,C++,Io,有没有一种方法可以将十六进制转换为十进制,并将十六进制转换为字符?例如,如果您有: string hexFile = string(argv[1]); ifstream ifile; if(ifile) ifile.open(hexFile, ios::binary); int i = ifile.get(); // I am getting hex form hexFile and want to char c = ifile.get(); // convert it to a dec

有没有一种方法可以将十六进制转换为十进制,并将十六进制转换为字符?例如,如果您有:

string hexFile = string(argv[1]);
ifstream ifile;
if(ifile)
  ifile.open(hexFile, ios::binary);
int i = ifile.get();  // I am getting hex form hexFile and want to 
char c = ifile.get(); // convert it to a decimal representation for int and char

谢谢。

整数就是整数就是整数。它仍然以二进制形式存储,您可以更改的只是演示文稿(即如何向用户显示)

要将字符显示为十进制数,只需将其转换为
int

char ch = 'a';
std::cout << static_cast<int>(ch) << '\n';
请注意,这仅适用于
a
以下的十六进制数字(即0到9)。

std::string s=“1F”;
int x;
std::stringstream-ss;
ssx;

std::coutI=static_cast(ifile.get());但这不起作用。我的意思是,如果我们有0x11,我不想让它以十进制打印49,而是11,有什么办法吗?@Napalidon
std::cout@Napalidon有什么问题,还是说你有字符串
“0x11”
,想要删除
“0x”
part?问题是我不想打印11,而是想将十六进制11转换为十进制11,即0x11=49,但我想要十进制的11,这样就可以将十六进制更改为0x0b,从而将十六进制0x11更改为十进制11?@Napalidon不,不会。你有微控制器/处理器的十六进制文件吗?(英特尔十六进制文件)?不,我没有。你想用它实现什么?你应该明确你到底想做什么。因为假设您有一个十六进制值0x1a5f->对应的十进制值1a5f甚至不存在。在这种情况下,您希望得到什么样的输出?
Hex
是一种表示法,类似于十进制
int
是一种数据类型,类似于
char
。这两个概念是完全正交的;所有4种组合都有意义。
char hex = 0x11;
int  dec = ((hex & 0xf0) >> 4) * 10 + (hex & 0x0f);
std::string s="1F";
int x;   
std::stringstream ss;
ss << std::hex << s;
ss >> x; 
std::cout<<x<<std::endl; //This is base 10 value
std::cout<<static_cast<char> (x)<<std::endl; //This is ASCII equivalent