2011-02-23 43 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);