【问题标题】:Convert ascii char[] to hexadecimal char[] in C在 C 中将 ascii char[] 转换为十六进制 char[]
【发布时间】:2013-05-07 07:26:33
【问题描述】:

我正在尝试将 ASCII 中的 char[] 转换为十六进制的 char[]。

类似这样的:

你好 --> 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 个字节合二为一以获得十六进制数。

我有这个函数,我在 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)

标签: c hex ascii


【解决方案1】:
#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 这个程序的结果存储在outword。不需要强制转换。
  • 我现在看到了。对不起。我只是在阅读时看到了 printf 。它工作正常。非常感谢。
  • 我添加了另一个与之相关的问题。你知道为什么会失败吗?
  • @BLUEPIXY outword+i*2 是什么意思。?
【解决方案2】:

替换这个

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

通过

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

【讨论】:

    【解决方案3】:

    使用%02X格式参数:

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

    更多信息可以在这里找到:http://www.cplusplus.com/reference/cstdio/printf/

    【讨论】:

      【解决方案4】:
      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);
      
          }
      
      
      }
      

      【讨论】:

        猜你喜欢
        • 2012-02-24
        • 2011-05-25
        • 2015-03-25
        • 2017-04-16
        • 2012-04-09
        • 2022-12-20
        • 2018-11-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多