[英]Shortest way to convert hex char to int in C?
我正在寻找C语言中最少的代码,以便将char转换为int,如果char不是有效的十六进制数字,则将-1(或任何错误标志)标记为int。
这是我想出的,还有更短的方法吗?
// input example
char input = 'f';
// conversion segment
int x = input - '0';
if (!((x >= 49 && x <= 54) || (x >= 0 && x <= 9))) x = -1;
if (x > 9) x -= 39;
// test print
printf("%d", x);
此代码采用ASCII并将所有256个字符的代码转换为256个不同的代码,部分将'0'-'9' 'A'-'F'
映射为0,1,...15
。
有关其他技巧和简化,请参阅帖子
unsigned char ch = GetData(); // Fetch 1 byte of incoming data;
if (!(--ch & 64)) { // decrement, then if in the '0' to '9' area ...
ch = (ch + 7) & (~64); // move 0-9 next to A-Z codes
}
ch -= 54; // -= 'A' - 10 - 1
if (ch > 15) {
; // handle error
}
试试这个功能:
isxdigit(c);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.