- 将十六进制转换为整数
- 将结果转换为类似于
char res = (char)intValue;
代码:
// this works if the string chars are only 0-9, A-F
// because of implemented mapping in `hex_to_int`
int hex_to_int(char c){
int first = c / 16 - 3;// 1st is dec 48 = char 0
int second = c % 16; // 10 in 1st16 5 in 2nd 16
// decimal code of ascii char 0-9:48-57 A-E: 65-69
// omit dec 58-64: :,;,<,=,>,?,@
// map first or second 16 range to 0-9 or 10-15
int result = first*10 + second;
if(result > 9) result--;
return result;
}
int hex_to_ascii(char c, char d){
int high = hex_to_int(c) * 16;
int low = hex_to_int(d);
return high+low;
}
int main(){
const char* st = "48656C6C6F3B";
int length = strlen(st);
int i;
char buf = 0;
for(i = 0; i < length; i++){
if(i % 2 != 0){
printf("%c", hex_to_ascii(buf, st[i]));
}else{
buf = st[i];
}
}
}
输出:
你好;
运行成功(总时间:59ms)