C++ 十六进制string转unsigned long long
小背景:
将"827716C408E1"转成unsigned long long类型的数据,然后传入 API
示例:827716C408E1 ==> 143447994665185
代码:
int Hex2Dec(char ch)
{
if (ch >= '0' && ch <= '9')
{
return ch - '0';
}
else if (ch >= 'A' && ch <= 'Z')
{
return ch - 'A' + 10;
}
else if (ch >= 'a' && ch <= 'z')
{
return ch - 'z' + 10;
}
else
return -1;
}
unsigned long long Hex2DecTwo2(const char *hex)
{
int len;
unsigned long long num = 0;
unsigned long long temp;
int bits;
int i;
len = strlen(hex);
for (i=0, temp=0; i<len; i++, temp=0)
{
temp = Hex2Dec( *(hex + i) );
bits = (len - i-1) * 4;
temp = temp << bits;
num = num | temp;
}
return num;
}
int main(){
string data = "827716C408E1";
unsigned long long res = Hex2DecTwo2(data.c_str());
cout << "res:" << res << endl;
system("pause");
return 0;
}
这是最近项目上遇到的类型转换问题的自验证过程,分享给大家,希望对小伙伴们有帮助!