Q:

# Input a hexadecimal value using scanf() in C

Program 1:

``````#include <stdio.h>

int main(void)
{
unsigned int value;

//input "123afc"
printf("Enter hexadecimal value without "0x": ");
//using %x (small x)
scanf("%x", &value);
printf("value = 0x%x or 0X%X\n", value, value);

//input "123AfC"
printf("Enter hexadecimal value without "0X": ");
//using X (capital x)
scanf("%X", &value);
printf("value = 0x%x or 0X%X\n", value, value);

return 0;
}``````

Output

```Enter hexadecimal value without "0x": 123afc
value = 0x123afc or 0X123AFC
Enter hexadecimal value without "0X": 123AFC
value = 0x123afc or 0X123AFC```

Program 2: Testing program with invalid hexadecimal value

``````#include <stdio.h>

int main(void)
{
unsigned int value;

//testing with invalue value
//while input, we are using alphabets
//which are greater than F
//as we know, hexadecimal allowes only
//A to F / a to f - which are equivelant
//to 10 to 15

scanf("%x", &value);
printf("value = %x\n", value);

return 0;
}``````

Output

```Enter a hexadecimal value: 123apd
value = 123a
```

Explanation:

In the hexadecimal value 123apd"p" is not a hexadecimal digit, thus, the input is valid/acceptable till valid digits. Given input 123pad is considered as 123a.