How to read hexadecimal numbers from input in C?

Viewed 142

I want to read a hexadecimal number from the user. I use C99.

My idea was to read a char and check by the character code what hexadecimal number it could be.

Here is the code:

#include <stdio.h>
int main() {
    char count;
    int c;
    printf("Enter hex value:\n");
    scanf("%c", &count);
    if (count >= 48 && count <= 57) {
        c = count - 48;
    }
    if (count >= 65 && count <= 70) {
        c = count - 55;
    }
    if (count >= 97 && count <= 102) {
        c = count - 87;
    }
    printf("%d", c);
    return 0;
}

But I think there should be easier ways. Because it can only read one number and not longer ones.

Is there anything that could help?

1 Answers

You can use scanf with %x:

#include <stdio.h>

int main() {
    int a;
    scanf("%x", &a);
    printf("%d", a);
}

Output:

a -> 10
ff -> 255
Related