gpt4 book ai didi

从 C 中的十六进制字符串转换为 ASCII 字符串

转载 作者:太空宇宙 更新时间:2023-11-04 03:54:35 25 4
gpt4 key购买 nike

我正在尝试将十六进制字符串转换为其等效的 ASCII。我得到一个字符串的“十六进制”值作为字符串,即我得到“41424344”而不是“ABCD”。我只需要提取 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;

}

最佳答案

从以下位置更改“s”变量行

int s = atoi(substr);

int s = strtol(substr, NULL, 16);

关于从 C 中的十六进制字符串转换为 ASCII 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17672639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com