我正在尝试将十六进制字符串转换为其等效的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”值成为十六进制值而不是int。怎么办呢?
更新
以下是我的回答后的内容:
#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;
}
答案 0 :(得分:1)
从
更改“s”变量行 int s = atoi(substr);
到
int s = strtol(substr, NULL, 16);