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
基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
