在C ++中将十六进制字符转换为int [英] Hex character to int in C++
问题描述
如何将十六进制字符而不是字符串更改为数值?
How can I change a hex character, not string, into a numerical value?
在输入这个问题时,我发现了许多关于如何将十六进制字符串转换为值的答案。但是,没有工作的字符。我记得在字符串的某个地方读取:
While typing this question, I found many answers on how to convert hex strings to values. However, none work for chars. I remember reading somewhere that this works for strings:
std::string mystr = "12345";
unsigned int myval;
std::stringstream(mystr) >> std::hex >> myval;
但是,如果我做 mystr [x]
在一个循环中,这段代码将不工作。我尝试添加一个新行与 std :: string temp = mystr [x]
并更改 std :: stringstream(mystr)
到 std :: stringstream(temp)
,但是这不工作。
However, if I do mystr[x]
in a loop, this code will not work. I have tried adding a new line with std::string temp = mystr[x]
and changing std::stringstream(mystr)
to std::stringstream(temp)
, but that's not working either.
那么我该怎么做呢?目前,我通过一个十六进制字符串(0123456789abcdef.find(mystr [x]);
)进行搜索,并使用该值的索引。
So how should I do this? Currently, I'm searching through a string of the hex chars ("0123456789abcdef".find(mystr[x]);
) and using the index for the value. However, since it searches, it's slow, even if it's only searching through 16 characters.
推荐答案
字符串。还可以使用 char
:
#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char val = 'A';
unsigned int myval;
std::stringstream ss;
ss << val;
ss >> std::hex >> myval;
cout << myval << endl;
}
这篇关于在C ++中将十六进制字符转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!