C语言实现1个字节Hex字符串转换为整型数据参考代码:
unsigned char str_to_int (char *str)
{
unsigned char i;
unsigned char ref[2];
unsigned char width[2];
if (str[2] != '\0' ||
!((str[0] >= '0' && str[0] <= '9') || (str[0] >= 'a' && str[0] <= 'f') || (str[0] >= 'A' && str[0] <= 'F')) ||
!((str[1] >= '0' && str[1] <= '9') || (str[1] >= 'a' && str[1] <= 'f') || (str[1] >= 'A' && str[1] <= 'F'))) {
printf("str_to_int err: data type error\n");
return 0;
}
for (i = 0; i < 2; i++) {
if (str[i] >= 'a' && str[i] <= 'f') {
ref[i] = 'a' - 10;
} else if (str[i] >= 'A' && str[i] <= 'F') {
ref[i] = 'A' - 10;
} else {
ref[i] = '0';
}
}
for (i = 0; i < 2; i++) {
width[i] = str[i] - ref[i];
}
return width[0]*16 + width[1];
}
|