2011-02-23 98 views
0

我打算做这样的程序:如何为十六进制数转换为ASCII使用C

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字符。

回答

3

,除非你真的想自己写的转换,你可以使用%x转换读取[F] scanf的十六进制数,或者你可以读一个字符串,并与(一个可能性)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); 
+0

上面的代码在只有一个数字的情况下工作。如何改变它以处理两位十六进制数的第一个数字? – 2011-02-23 09:15:07

+0

@ Z缓冲区:在大多数情况下,您只需重复尽可能多的数字。 – 2011-02-23 15:27:09

+0

如果删除了16 *值,那么这将起作用,然后他的结果乘以16^n,其中n是数字的位置。 – 2011-02-24 08:07:25

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; 
1

把你的两个字符为字符数组,空终止它,并使用strtol()从'<stdlib.h>'(docs)将其转换为整数。

char s[3]; 

s[0] = '2'; 
s[1] = 'a'; 
s[2] = '\0'; 

int i = strtol(s, null, 16);