之前写了一篇文章,说是一个要修改一个代码,很多人评论说代码说得不清不楚,不过在评论说又解释了一波之后,大家至少对这个代码有理解了,至少知道这个代码是做什么事情了。
如果是你,会不会修改这段代码?
我这次说说的是,我今天看到一个读者评论,说了他了一个想法,这真的让我觉得茅塞顿开。
我们正常的情况下,如果需要把字符 ‘a’ 转换成10进制 10,用到的是下面这段代码
unsigned int Hex2Int(char c) {
if (c >= '0' && c <= '9') {
return (unsigned int) (c - '0');
} else {
return (unsigned int)(c - 'a'+10);
}
}
这个读者给出的方案是,用数组,因为他的这个评论,我就突然觉得非常不错的一个写法,在这里特别想分享给大家看看
unsigned int CharToHex(char c) {
unsigned int StringAsciiToIntArray[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
unsigned int i = 0;
for (i = 0; i < sizeof(StringAsciiToIntArray)/sizeof(StringAsciiToIntArray[0]); i++) {
if (c == StringAsciiToIntArray[i]) return i;
}
return i;
}
然后我们应用在实际的代码中运行看看
#include <stdio.h>
#include <stdlib.h>
unsigned int Hex2Int(char c) {
if (c >= '0' && c <= '9') {
return (unsigned int) (c - '0');
} else {
return (unsigned int)(c - 'a'+10);
}
}
unsigned int CharToHex(char c) {
unsigned int StringAsciiToIntArray[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
unsigned int i = 0;
for (i = 0; i < sizeof(StringAsciiToIntArray)/sizeof(StringAsciiToIntArray[0]); i++) {
if (c == StringAsciiToIntArray[i]) return i;
}
return i;
}
int main() {
unsigned int val = 0;
char buffer[5] = {"1234"}; // 16进制1234
const unsigned int totalread = 3;
printf("0x%x %d\n", atoi(buffer), atoi(buffer));
val = Hex2Int(buffer[totalread - 3]) * 0x1000;
val += Hex2Int(buffer[totalread - 2]) * 0x0100;
val += Hex2Int(buffer[totalread - 1]) * 0x0010;
val += Hex2Int(buffer[totalread]);
printf("0x%x ,%d\n", val, val);
val = 0;
val = CharToHex(buffer[totalread - 3]) * 0x1000;
val += CharToHex(buffer[totalread - 2]) * 0x0100;
val += CharToHex(buffer[totalread - 1]) * 0x0010;
val += CharToHex(buffer[totalread]);
printf("0x%x ,%d\n", val, val);
char* p_end;
val = strtol(&buffer, &p_end, 16);
if (*p_end != '\0') {
printf("strtol error\n");
return -1;
}
printf("0x%x ,%d\n", val, val);
return 0;
}
代码输出
(base) crisqifawei@CRISQIFAWEI-MC0 task_scheduling_core % gcc -w tt.c && ./a.out
0x4d2 1234
0x1234 ,4660
0x1234 ,4660
0x1234 ,4660
就这样!