拥有这段代码:
int main(void)
{
char c;
int hex;
....
}
Run Code Online (Sandbox Code Playgroud)
如果c是'a'我想hex成为10.如果c有'f',hex应该是15.我知道如何完成这个任务的整数(c - '0'虽然这不赞成)或字符串(使用sprintf或strtol)但我不知道如何完成这个简单的任务一般.
if (c >= '0' && c <= '9')
hex = c - '0';
else if (c >= 'a' && c <= 'z')
hex = c - 'a' + 10;
else if (c >= 'A' && c <= 'Z')
hex = c - 'A' + 10;
else
abort();
Run Code Online (Sandbox Code Playgroud)
要捕获错误的输入,您可以添加
if (hex >= base) /* base would be e.g. 16 */
abort();
Run Code Online (Sandbox Code Playgroud)
或者当base固定时,您可以限制上限(例如,c <= 'f'而不是c <= 'z').第一种方法更灵活,允许例如更大的碱基或转换八进制数.