0

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.

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

3 Comments

The code above works if there's only one digit. How would it be changed to deal with the first digit in a two-digit hex number?
@Z-buffer: for the most part, you just repeat for as many digits as necessary.
This works if 16 * value is removed, and then he result is multiplied by 16^n, where n is the position of the digit.
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;

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.