将十六进制字符串转换为unsigned int问题C ++ [英] Converting hex string to unsigned int issue C++

查看:183
本文介绍了将十六进制字符串转换为unsigned int问题C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在设计一个代码,给出的一个指令是获取十六进制字符串的前两位数字并执行所需的操作。小于A的所有内容都被考虑在内。任何大于那不是,它只是采取下一个数字。



这是转换它的行:

  int x = atoi(hex.c_str); 

我做错了什么?

解决方案

我假设这是你的意思 - 你只想将一个字符串的前两个十六进制数字转换为无符号整数。我还假设字符串只包含有效的十六进制数字。如果你想验证字符串,你需要为它写一些额外的代码。



使用 strtoul 一个十六进制字符串转换为无符号整数。还可以使用字符串类的 substr()方法仅提取十六进制字符串的初始2位数字。

  #include< string> 
#include< cstdio>
#include< cstdlib>

int main()
{
std :: string myhex =abcdef;
unsigned int x = strtoul(myhex.substr(0,2).c_str(),NULL,16);
printf(x =%d \\\
,x);
}

这将是您的输出(即 0xab = 171 ):

  x = 171 
p $ p>

I am currently designing a code and one of the instructions given is to get the first two digits of a hex string and do a desired operation. Everything that is less than A is taken into account. Anything greater than that is not, it just takes the next number. Which messes up the code.

Here is the line which converts it:

int x = atoi(hex.c_str);

What am I doing wrong?

解决方案

I'm assuming this is what you meant - you'd like to convert only the first two hexadecimal digits of a string to an unsigned integer. I'm also assuming that the string contains only valid hexadecimal digits. If you want to validate the string, you need to write some extra code for that.

Use strtoul to convert a hex string to unsigned integer instead. Also use substr() method of the string class to extract only the initial 2 digits of the hexadecimal string.

#include <string>
#include <cstdio>
#include <cstdlib>

int main()
{
    std::string myhex = "abcdef";
    unsigned int x = strtoul(myhex.substr(0, 2).c_str(), NULL, 16);
    printf("x = %d\n", x);
}

This would be your output (i.e. 0xab = 171):

x = 171

这篇关于将十六进制字符串转换为unsigned int问题C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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