在C语言中将ASCII字符数组转换为十六进制字符数组

16

我正在尝试将ASCII字符数组转换为十六进制字符数组。

类似这样:

hello --> 68656C6C6F

我想通过键盘读取字符串。它必须是16个字符长。

这是我的代码。我不知道如何进行这个操作。我了解了strol,但我认为它只能将str数字转换为int hex...

#include <stdio.h>
main()
{
    int i = 0;
    char word[17];

    printf("Intro word:");

    fgets(word, 16, stdin);
    word[16] = '\0';
    for(i = 0; i<16; i++){
        printf("%c",word[i]);
    }
 }

我正在使用fgets,因为我读取的比fgets更好,但如果需要,我可以进行更改。

与此相关的是,我试图将读取的字符串转换为uint8_t数组,将每2个字节合并为一个16进制数。

我有这个函数,在arduino中经常使用,所以我认为它应该在普通的C程序中没有问题。

uint8_t* hex_decode(char *in, size_t len, uint8_t *out)
{
    unsigned int i, t, hn, ln;

    for (t = 0,i = 0; i < len; i+=2,++t) {

            hn = in[i] > '9' ? (in[i]|32) - 'a' + 10 : in[i] - '0';
            ln = in[i+1] > '9' ? (in[i+1]|32) - 'a' + 10 : in[i+1] - '0';

            out[t] = (hn << 4 ) | ln;
            printf("%s",out[t]);
    }
    return out;

但是,每当我在我的代码中调用该函数时,就会出现分段错误。

将此代码添加到第一个答案的代码中:

    uint8_t* out;
    hex_decode(key_DM, sizeof(out_key), out);

我尝试传递所有必要的参数并从输出数组中获取所需内容,但失败了...


uint8_t* out; --> uint8_t* out = calloc(sizeof(out_key), sizeof(*out)); 或者使用 strlen(key_DM)+1 替代 sizeof(out_key) - BLUEPIXY
4个回答

14
#include <stdio.h>
#include <string.h>

int main(void){
    char word[17], outword[33];//17:16+1, 33:16*2+1
    int i, len;

    printf("Intro word:");
    fgets(word, sizeof(word), stdin);
    len = strlen(word);
    if(word[len-1]=='\n')
        word[--len] = '\0';

    for(i = 0; i<len; i++){
        sprintf(outword+i*2, "%02X", word[i]);
    }
    printf("%s\n", outword);
    return 0;
}

我只是举例打印。但我想把这个字符串保存在另一个字符串中。我该怎么做转换? - Biribu
1
@Biribu,这个程序的结果存储在outword中。强制转换是不必要的。 - BLUEPIXY
1
@BLUEPIXY,“outword+i*2”是什么意思? - S Andrew
@BLUEPIXY,我认为这不正确,因为在我的情况下,它会正确地保存在索引0、1、2、3...根据你在答案中的C代码,我的输出是255,单词大小也是255。 - S Andrew
@SAndrew char word[17], outword[33];//17:16+1, 33:16*2+1. 我不知道你的具体情况。 - BLUEPIXY
显示剩余4条评论

5

替换这个

printf("%c",word[i]);

by

printf("%02X",word[i]);

4

0
void atoh(char *ascii_ptr, char *hex_ptr,int len)
{
    int i;

    for(i = 0; i < (len / 2); i++)
    {

        *(hex_ptr+i)   = (*(ascii_ptr+(2*i)) <= '9') ? ((*(ascii_ptr+(2*i)) - '0') * 16 ) :  (((*(ascii_ptr+(2*i)) - 'A') + 10) << 4);
        *(hex_ptr+i)  |= (*(ascii_ptr+(2*i)+1) <= '9') ? (*(ascii_ptr+(2*i)+1) - '0') :  (*(ascii_ptr+(2*i)+1) - 'A' + 10);

    }


}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接