What is Binary?
A binary number is a numerical value expressed in a base 2 numeral system, utilizing only two symbols: 0 and 1.
Examples
Consider a scenario where we have the hexadecimal value A12C. Next, we need to determine the binary equivalent of this hexadecimal value.
Hexadecimal number=A12C
Binary value equivalent to A is 1010
Binary value equivalent to 1 is 0001
Binary value equivalent to 2 is 0010
Binary value equivalent to C is 1100
Hence, the binary representation corresponding to A12C is 1010000100101100.
Note: To convert hexadecimal into a binary number, the binary value of each digit of a hexadecimal number is evaluated and combined to get the binary number of a given hexadecimal number.
Let's understand through an example.
#include<stdio.h>
void hextobin(char b[]);
void main()
{
char hex[]="A12C";
hextobin(hex);
}
void hextobin(char hex[])
{
int i=0;
while(hex[i])
{
switch(hex[i])
{
case '0':
printf("0000");
break;
case '1':
printf("0001");
break;
case '2':
printf("0010");
break;
case '3':
printf("0011");
break;
case '4':
printf("0100");
break;
case '5':
printf("0101");
break;
case '6':
printf("0110");
break;
case '7':
printf("0111");
break;
case '8':
printf("1000");
break;
case '9':
printf("1000");
break;
case 'A':
printf("1010");
break;
case 'a':
printf("1010");
break;
case 'B':
printf("1011");
break;
case 'b':
printf("1011");
break;
case 'C':
printf("1100");
break;
case 'c':
printf("1100");
break;
case 'D':
printf("1101");
break;
case 'd':
printf("1101");
break;
case 'E':
printf("1110");
break;
case 'e':
printf("1110");
break;
case 'F':
printf("1111");
break;
case 'f':
printf("1111");
break;
}
i++;
}}
In the provided code snippet, we aim to determine the binary representation of the hexadecimal value " A12C ". Initially, we save this value in a character array called hex, followed by passing this array to a function named hextobin. Within hextobin, the binary equivalent is computed by iterating over each element in the array using a while loop. The binary value for each element is determined by a switch statement.
Output
1010000100101100