我正在尝试将十六进制字符串转换为其等效的 ASCII。我得到了一个字符串的“十六进制”值作为字符串,即代替“ABCD”,我得到“41424344”。我只需要提取 41 这将是我的十六进制值并重新编码为“ABCD”。这就是我所拥有的。
int main(int argc, char *argv[]){
char *str = "ABCD";
unsigned int val = 0;
int i = 0;
int MAX = 4;
for (i = 0; i<MAX; i++){
val = (str[i] & 0xFF);
//printf("dec val= %d\n", val);
//printf("hex val= %02x\n", val);
}
val = 0;
char *hexstr = "41424344";
char *substr = (char*)malloc(3);
char *ptr = hexstr;
for (i = 0; i<8; i++){
strncpy(substr, ptr, 2);
printf("substr = %s\n", substr);
int s = atoi(substr);
printf("s= %d\n", s);
ptr= ptr+2;
i = i+2;
}
return 0;
}
事情是从这里开始,我必须将这个“s”值设为十六进制值而不是整数。如何才能做到这一点?
更新:
以下是您回答后的内容:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
char *str = "ABCD";
unsigned int val;
val = 0;
int i = 0;
int MAX = 4;
for (i = 0; i<MAX; i++){
val = (str[i] & 0xFF);
//printf("dec val= %d\n", val);
//printf("hex val= %02x\n", val);
}
val = 0;
char *hexstr = "41424344";
char *substr = (char*)malloc(3);
char *ptr = hexstr;
char *retstr = (char *)malloc(5);
char *retptr = retstr;
for (i = 0; i<8; i+1){
strncpy(substr, ptr, 2);
printf("substr = %s\n", substr);
int s = strtol(substr, NULL, 16);
printf("s= %d\n", s);
ptr= ptr+2;
i = i+2;
sprintf(retptr, "%c", s);
retptr = retptr +1;
}
printf("retstr= %s\n", retstr);
return 0;
}