C program that takes an 8-bit number and Convert it to hexadecimal format
Posted by Samath
Last Updated: January 01, 2017

Write a C program that takes an 8-bit number through console as input. Convert it to hexadecimal format and display it as output.

Code:

#include <stdio.h>
#include <string.h>
int bin2dec(char *bin); // Declares Function With Characters
int main() // Main Program Starts
{
	char bin[80] = ""; // Declares Character Array
	char *p; // Declares Character Pointer
	int dec; // Saves Variable Name Into Memory
	while(strcmp(bin,"0")) // Start While Loop With String Compare Condition
	{
		printf("\nPlease Enter an 8-Bit Binary Number (Press 0 To EXIT): "); // Prompts For User Input
		fgets(bin, sizeof(bin), stdin); // Reads Characters From Stream And Stores Them As A C String
		// Until (num-1) Characters Have Been Read Or Either a A
		// Newline Or A The End-of-File Is Reached, Whichever Comes First
		if ((p = strchr(bin,'\n')) != NULL) // If Variable P Equals A String Character Condition...
		{
			*p = '\0'; // If False Condition Declare Null
		}
		dec = bin2dec(bin);
		if (dec) printf("\n\nDecimal = %d\nHexadecimal = 0x%04X\n ",dec,dec); // Displays Decimal And Hexadecimal Values
	}
	getchar(); // Pauses Program
	return 0; // Return To Main
}

int bin2dec(char *bin)
{
	int b , k, n; // States Multiple Variables
	int len, sum = 0; // States Variable Into Memory
	len = strlen(bin) - 1;
	for(k = 0; k <= len; k++) // Initialize For Loop With Counter
	{
		b = 1;
		n = (bin[k] - '0'); // Char To Numeric Value
		if ((n > 1) || (n < 0)) // Makes Sure It Is A Binary Input
		{
			puts("\n\n ERROR! BINARY has only 1 and 0!\n"); // Displays Error Message If Condition Is Not Met
			return (0);
		}
	b = b<<(len-k);
	sum = sum + n * b; // Sums All The Binary Positions
	printf("\n+%d*%d ",n,b); // Displays Process
	}
	return(sum); // Returns To Sum Loop
}