C program that takes a 2 digit hexadecimal number and display it in binary format
Posted by Samath
Last Updated: January 01, 2017

Write a C program that takes a 2 digit hexadecimal number from the user through console and display it in binary format.

Code:

#include <stdio.h>
int main (int argc, char * const argv[]) {
	// In this part we create an array of 2 characters
	char number[2];
	int i;
	printf("Please enter a 2 digit hexadecimal number\n");
	// Here it scans the number given and stores it in the array
	scanf("%s", number);
	// It starts to create a loop from 0 to 2 checking each number
	for(i=0; i<2; i++){
	//If the number is equal to one number in hexadecimal it print in
	//the binary format
	if(number[i] == '0'){
		printf("0000");
	}
	else if(number[i] =='1'){
		printf("0001");
	}
	else if(number[i] == '2'){
		printf("0010");
	}
	else if(number[i] == '3'){
		printf("0011");
	}
	else if(number[i] == '4'){
		printf("0100");
	}
	else if(number[i] == '5'){
		printf("0101");
	}
	else if(number[i] == '6'){
		printf("0110");
	}
	else if(number[i] == '7'){
		printf("0111");
	}
	else if(number[i] == '8'){
		printf("1000");
	}
	else if(number[i] == '9'){
		printf("1001");
	}
	else if(number[i] == 'A' || number[i] == 'a'){
		printf("1010");
	}
	else if(number[i] == 'B' || number[i] == 'b'){
		printf("1011");
	}
	else if(number[i] == 'C' || number[i] == 'c'){
		printf("1100");
	}
	else if(number[i] == 'D' || number[i] == 'd'){
		printf("1101");
	}
	else if(number[i] == 'E' || number[i] == 'e'){
		printf("1110");
	}
	else if(number[i] == 'F' || number[i] == 'f'){
		printf("1111");
	}

	else {
		printf( "You did not follow the rules\n" );
	}
	}
	printf( "\n" );
	return 0;
}