gpt4 book ai didi

c - 在 C 中将 ASCII 转换为 HEX 时跳过特殊字符

转载 作者:太空宇宙 更新时间:2023-11-04 06:51:18 26 4
gpt4 key购买 nike

我需要帮助来获得仅针对字母数字字符(不包括特殊字符)的 ascii 到十六进制数据输出。

Input String is: 86741-30011
Expected result is: 38363734313330303131
Actual Result is: 3836373431

输出在非字母数字字符后中断。它只包含输出字符串,直到非字母数字字符。

代码:

int main(void){
char word[12] = { '8', '6','7','4','1','-','3','0','0','1','1'};
char outword[20];
int i, len;
len = strlen(word);
printf("Input string: %s\n", word);
//printf("Total length: %d\n", len);
if(word[len-1]=='\n') word[--len] = '\0';
for(i = 0; i<len; i++) {
if (isalnum(word[i]) == 0) {
printf("%c is not an alphanumeric character.\n", word[i]);
} else {
sprintf(outword+i*2 , "%02X", word[i]);
}
}
printf("Hex output:%s\n", outword); return 0;
}

任何人都可以帮助我获得预期的输出吗?

提前致谢。

最佳答案

使用不同的变量进行循环旋转并将数据添加到数组中。

#include <stdio.h>

int main(void){
char word[12] = { '8', '6','7','4','1','-','3','0','0','1','1'};
char outword[20];
int i, j, len;
len = strlen(word);
printf("Input string: %s\n", word);
//printf("Total length: %d\n", len);
if(word[len-1]=='\n') word[--len] = '\0';
for(i = 0,j=0; i<len; i++) {
if (isalnum(word[i]) == 0) {
printf("%c is not an alphanumeric character.\n", word[i]);
} else {
sprintf(outword+j*2 , "%02X", word[i]);
j=j+1;
}
}
printf("Hex output:%s\n", outword); return 0;
}

此代码将为您提供预期结果 38363734313330303131。

关于c - 在 C 中将 ASCII 转换为 HEX 时跳过特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50715481/

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