C – Read Hexadecimal Number using Scanf()
To read a hexadecimal number entered by user via standard input in C language, use scanf() function.
scanf() reads input from stdin(standard input), according to the given format and stores the data in the given arguments.
So, to read a hexadecimal number from console, give the format and argument to scanf() function as shown in the following code snippet.
</>
Copy
int n;
scanf("%x", n);
Here, %x
is the format to read a hexadecimal number and this value is stored in variable n
.
Examples
In the following example, we read a hexadecimal number input by the user in standard input to a variable n
using scanf() function.
main.c
</>
Copy
#include <stdio.h>
int main() {
int n;
printf("Enter hex : ");
//read input from user to "n"
scanf("%x", &n);
//print to console
printf("You entered %d\n", n);
return 0;
}
Output
Enter hex : AF
You entered 175
Program ended with exit code: 0
Enter hex : B
You entered 11
Program ended with exit code: 0
Enter hex : -C
You entered -12
Program ended with exit code: 0
Conclusion
In this C Tutorial, we learned how to read a hexadecimal number entered by user via standard input using scanf() function.