开发者

How to convert a hexadecimal number into Ascii in C

I plan to make a program like this:

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

The problem I'm having is turning the two characters into a hexadeci开发者_StackOverflowmal number and then turning that into a decimal number. Once I have a decimal number I can display the ascii character.


Unless you really want to write the conversion yourself, you can read the hex number with [f]scanf using the %x conversion, or you can read a string, and convert with (for one possibility) strtol.

If you do want to do the conversion yourself, you can convert individual digits something like this:

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;


put your two characters into a char array, null-terminate it, and use strtol() from '<stdlib.h>' (docs) to convert it to an integer.

char s[3];

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜