node ninja
node ninja

Reputation: 33056

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.

Upvotes: 0

Views: 17335

Answers (3)

Lee
Lee

Reputation: 13542

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

Upvotes: 1

Tony Delroy
Tony Delroy

Reputation: 106246

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;

Upvotes: 2

Jerry Coffin
Jerry Coffin

Reputation: 490663

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

Upvotes: 3

Related Questions