简体   繁体   中英

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 hexadecimal 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM