# Convert hex to binary

Here you will learn how to convert hex to binary. These numeral systems both have a base that is an exact power of 2: 16 = 2^{4} and 2 = 2^{1}. Because of that, the conversion between the two systems is very, very easy. If you know how to convert between the other notations you will be surprised at how easy this is :)

## Online hex to binaryconverter

Advertise on this site. I promise you will like the rates :)

## The algorithm

Hex to binary is probably the easiest conversion between the number systems. To turn a hexadecimal value to a binary number do the following

- Take each hex digit and replace it with its binary equivalent.
- There is no second step. That's it – told ya its easy ;-)

Here is a table that contains the hex-to-binary mappings:

## Examples

64

_{16} = ?

_{2}
6

_{16} = 0110

_{2}, 4

_{16} = 0100

_{2}
64

_{16} = 01100100

_{2} or 0110 0100

_{2}
F1A80

_{16} = ?

_{2}
F

_{16} = 1111

_{2}, 1

_{16} = 000

_{12}, A

_{16} = 1010

_{2}, 8

_{16} = 1000

_{2}, 0

_{16} = 0000

_{2}
F1A80

_{16} = 11110001101010000000

_{2} or 1111 0001 1010 1000 0000

_{2}
## Creating a C converting program

* The C source code of the example implementation is available in GitHub or you can directly download the zipped code: **hex-to-bin.zip*

The hex to binary algorithm doesn't
have any fancy tricks. It is straight forward work
with strings.

We begin by reading a hex number, up to
100 digits long. Of course we reserve one byte for the *null*
terminating symbol. That's why the size of the array *hex*
is 101 elements. After we read the input we begin the conversion in
the *hexToBinary*
function.

int main(void)
{
char hex[101];
int length;
int validation;
char *binary;
scanf("%100s", hex);
length = strlen(hex);
binary = hexToBinary(hex, length);
printf("%s in hexadecimal is %sin binary\n", hex, binary);
return 0;
}

char *hexToBinary(char *hex, int length)
{
char *binary = (char*) malloc(length * 5 + 1);
if(binary == NULL)
exit(1);
while(*hex != '\0')
{
char *binaryValue = valueOf(*hex);
while(*binaryValue != '\0')
*binary++ = *binaryValue++;
++hex;
}
*binary = '\0';
binary -= length * 5;
return binary;
}

The *binary*
char pointer holds the result. Now, looking at the table above you
see that for each hex digit we need exactly 4 binary digits. Plus we
want to insert spaces between the digits, so the result is easier to
read. That's why, we allocate 5 times the length of the input + 1
element for the terminating symbol.

Then we loop through the hex value and
take the corresponding binary string with a switch. The inner while
just copies the current binary number into the pointer that holds the
final result. Finally, we reset the *binary*
pointer, so that it points to the beginning of the bin value.

That's it, really simple – just
handling strings.

See also how to convert from: