如何从字符串十六进制中获取十进制数:
我拥有unsigned char* hexBuffer = "eb89f0a36e463d";.
并且我unsigned char* hex[5] ={'\\','x'};.
从前hexBuffer两个char 复制"eb"到hex[2] = 'e'; hex[3] = 'b';.
现在我有字符串"\xeb"或"\xEB"内六角.
因为我们都知道0xEB它的ahexdecimal,我们可以转换为235十进制.
我怎样才能转换"\xEB"成235(int)?
(感谢jedwards)
我的答案(也许对某人有用):
/*only for lower case & digits*/
unsigned char hash[57] ="e1b026972ba2c787780a243e0a80ec8299e14d9d92b3ce24358b1f04";
unsigned char chr =0;
int dec[28] ={0}; int i = 0;int c =0;
while( *hash )
{
c++;
(*hash >= 0x30 && *hash <= 0x39) ? ( chr = *hash - 0x30) : ( chr = *hash - 0x61 + 10);
*hash++;
if ( c == 1) dec[i] = chr * 16; else{ dec[i] += chr; c = 0; dec[i++];}
}
Run Code Online (Sandbox Code Playgroud)
您想要的功能被调用 sscanf.
http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/
int integer;
sscanf(hexBuffer, "%x", &integer);
Run Code Online (Sandbox Code Playgroud)
在C++ 11中,您可以使用字符串之一到无符号整数类型和积分转换函数:
long i = std::stol("ff", nullptr, 16); // convert base 16 string. Accepts 0x prefix.
Run Code Online (Sandbox Code Playgroud)
当然,这要求您的字符串表示可以适合表达式LHS上的整数类型的数字.