【问题标题】:How to convert a hexadecimal number into Ascii in C如何在C中将十六进制数转换为Ascii
【发布时间】:2011-02-23 06:46:33
【问题描述】:

我打算做一个这样的程序:

loop

 read first character
 read second character

 make a two-digit hexadecimal number from the two characters
 convert the hexadecimal number into decimal
 display the ascii character corresponding to that number.

end loop

我遇到的问题是将这两个字符转换为十六进制数,然后将其转换为十进制数。一旦我有一个十进制数字,我就可以显示 ascii 字符。

【问题讨论】:

    标签: c ascii hex


    【解决方案1】:

    除非您真的想自己编写转换,您可以使用 [f]scanf 使用 %x 转换来读取十六进制数字,或者您可以读取一个字符串,然后使用(一种可能性)strtol 进行转换。

    如果您确实想自己进行转换,您可以像这样转换单个数字:

    if (ixdigit(ch))
        if (isdigit(ch))
            value = (16 * value) + (ch - '0');
        else
            value = (16 * value) + (tolower(ch) - 'a' + 10);
    else
        fprintf(stderr, "%c is not a valid hex digit", ch);
    

    【讨论】:

    • 如果只有一位数字,上面的代码有效。如何改变处理两位十六进制数字中的第一个数字?
    • @Z-buffer:在大多数情况下,您只需根据需要重复尽可能多的数字。
    • 如果 16 * 值被删除,然后他的结果乘以 16^n,其中 n 是数字的位置。
    【解决方案2】:
    char a, b;
    
    ...read them in however you like e.g. getch()
    
    // validation
    if (!isxdigit(a) || !isxdigit(b))
        fatal_error();
    
    a = tolower(a);
    b = tolower(b);
    
    int a_digit_value = a >= 'a' ? (a - 'a' + 10) : a - '0';
    int b_digit_value = b >= 'a' ? (b - 'a' + 10) : b - '0';
    int value = a_digit_value * 0x10 + b_digit_value;
    

    【讨论】:

      【解决方案3】:

      将您的两个字符放入一个 char 数组,以空值结尾,然后使用来自 '' (docs) 的 strtol() 将其转换为整数。

      char s[3];
      
      s[0] = '2';
      s[1] = 'a';
      s[2] = '\0';
      
      int i = strtol(s, null, 16);
      

      【讨论】:

        猜你喜欢
        • 2016-06-27
        • 2013-12-22
        • 2016-09-27
        • 1970-01-01
        • 1970-01-01
        • 2011-08-06
        • 2017-10-26
        • 2013-05-07
        • 2012-12-10
        相关资源
        最近更新 更多