在 C++ 中将十六进制字符转换为 int

Hex character to int in C++(在 C++ 中将十六进制字符转换为 int)

本文介绍了在 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

基础教程推荐