首页 > 解决方案 > 如何读取多个字符并转换为 Ascii?

问题描述

我有一个用空格分隔的十六进制格式的输入:(例如)4A 49 5A 我需要读取该行并打印同一行但以 Ascii 格式:JIZ 我实际上做了相反的操作(ascii 到十六进制)但不能使其适应所需的情况。我只能使用stdio.hstring.h 下面是代码 ascii 到 hex。

    char *line = NULL;
    char *token;
    size_t len = 0;
    ssize_t read = 0;

    read = getline(&line, &len, stdin);
    if (read == -1) {
        printf("n/a\n");
        return 0;
    }
      
    while ((token = strsep(&line, " ")) != NULL) {
        printf("%X ", *token);
    }
    return 1;

还有我的尝试让十六进制到 ascii 工作。据我了解,read在这种情况下,变量也无法正常工作。

    char *token;
    size_t len = 0;
    ssize_t read = 0;
    int e;

    read = getline(&line, &len, stdin);
    if (read == -1) {
        printf("n/a\n");
        return 0;
    }
    printf("%zd", read);
    for (int i = 0; i < (sizeof(read)/sizeof(char)); i++) {
        e = line[i];
        //printf("%c", line[i]);
        //printf("%d ", e);
    }

    // while ((token = strsep(&line, " ")) != NULL) {
    //     printf("%d", (int)*token);
    //}
    return 1;

标签: chexascii

解决方案


推荐阅读