[英]How to convert a hexadecimal number into Ascii in 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字符。
除非您真的想自己編寫轉換,否則可以使用%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);
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;
將您的兩個字符放入char數組中,以null終止,然后使用'<stdlib.h>'( docs )中的strtol()
將其轉換為整數。
char s[3];
s[0] = '2';
s[1] = 'a';
s[2] = '\0';
int i = strtol(s, null, 16);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.