我有一个字符串,如下所示。 std :: string myString =“0005105C9A84BE03”;
我希望将精确数据保存在某个整数上,说“long long int” long long int myVar = 0005105C9A84BE03;
当我打印myVar时,我期待输出1425364798979587。
我试图使用atoi,strtol stroi,strtoll,但没有任何效果。
知道怎么解决吗?
答案 0 :(得分:0)
以下内容应该有效:
#include <iostream>
#include <sstream>
int main()
{
std::string hexValue = "0005105C9A84BE03"; // Original string
std::istringstream converter { hexValue }; // Or ( ) for Pre-C++11
long long int value = 0; // Variable to hold the new value
converter >> std::hex >> value; // Extract the hex value
std::cout << value << "\n";
}
此代码使用std::istringstream
通过std::hex
流操作符的使用从std::string
转换为long long int
。
答案 1 :(得分:0)
有一个函数列表可以从字符串转换为不同的整数类型,如:
stol将字符串转换为long int(函数模板)
stoul将字符串转换为无符号整数(函数模板)
strtol将字符串转换为长整数(函数)
他们还有一些。请查看http://www.cplusplus.com/reference/string/stoul在文档的最后,您可以找到不同数据类型的替代函数。
所有他们都拥有&#34;基地&#34;参数。要从十六进制转换,只需设置base=16
。
std::cout << std::stoul ("0005105C9A84BE03", 0, 16) << std::endl;