Input a hexadecimal value using scanf() in C

Here, we are going to learn how to input a hexadecimal value using scanf() in C programming language?
By IncludeHelp Last updated : March 10, 2024

Here, we have to declare an unsigned int variable and input a value in hexadecimal format.

Input a hexadecimal value using scanf()

To input a value in hexadecimal format – we use "%x" or "%X" format specifier and to print the value in hexadecimal format – we use same format specifier "%x" or "%X".

  • "%x" – prints value with lowercase alphabets (a to f)
  • "%X" – prints value with uppercase alphabets (A to F)

Note: In scanf(), you can use both of the format specifiers "%x" or "%X" – it does not affect to user input, but in the printf()"%x" or "%X" matters for printing alphabets in hexadecimal value (a to f or A to F).

Example

#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

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

	printf("Enter a hexadecimal value: ");
	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.

C scanf() Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.