Hex character to int in C++(在 C++ 中将十六进制字符转换为 int)
问题描述
如何将十六进制字符而不是字符串更改为数值?
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]);) 并使用索引作为值.但是,由于它搜索,所以即使只搜索 16 个字符,它也很慢.
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.
http://ideone.com/dIyD4
推荐答案
您已经有了一个适用于字符串的解决方案.chars 也可以使用它:
You already have a solution that works with strings.  Use it for chars too:
#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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中将十六进制字符转换为 int
 
				
         
 
            
        - 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01
- C++ 协变模板 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
 
						 
						 
						 
						 
						 
				 
				 
				 
				