在C ++中将十六进制字符转换为int [英] Hex character to int in C++

查看:155
本文介绍了在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]); )进行搜索,并使用该值的索引。

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

推荐答案

字符串。还可以使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆