[英]How to convert a String into Unsigned Long. With a twist
Hello I have a string parser who receives as its input a hex number: For Example: String X="0x120005f38" 您好,我有一个字符串解析器,它接收一个十六进制数字作为输入:例如:String X =“ 0x120005f38”
As you can see the number is in HEX, how do I convert this to unsigned long? 如您所见,该数字以十六进制表示,该如何将其转换为无符号长整数?
If this was decimal based string I could use the string to unsigned long function. 如果这是基于十进制的字符串,则可以使用该字符串进行无符号长函数处理。 I am guessing there are a couple of steps, and I am not sure what order or functions to use. 我猜有几个步骤,我不确定要使用什么顺序或功能。 1)Where I need to convert Hex into decimal 2)and String into unsigned long. 1)我需要将十六进制转换为十进制2)和字符串转换为无符号长整数。
This seems very tricky to me, any ideas? 这对我来说似乎很棘手,有什么想法吗?
Use strtoul
: 使用strtoul
:
strtoul("0x120005f3", 0, 0);
strtoul
reference on cplusplus.com . 关于cplusplus.com的 strtoul
参考。 See how that works on Codepad . 看看如何在Codepad上工作 。
EDIT: Changed to strtoul
, did not notice that unsigned long
is required. 编辑:更改为strtoul
,没有注意到需要unsigned long
。
您可以指定strtoul
函数的base
参数,该参数允许在字符串上使用0x
前缀。
Using streams: 使用流:
#include <iostream>
#include <sstream>
int main()
{
const char* X="0x120005f38";
std::stringstream ss(X);
long long var; //your value is too large for my long
ss >> std::hex >> var;
std::cout << var << ' ' << std::hex << var << '\n';
}
如果从字面上看这是您的代码,请不要使其成为带有0x前缀的文字整数: int x = 0x120005f38;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.