logo for matrixlab-examples.com
leftimage for matrixlab-examples.com

Hex to binary: two solutions in Matlab 

To convert a value from hex to binary, we first need to know what a hexadecimal number is.

A major numbering system used in digital systems is the hex system, also known as base 16. In this system, the numbers are counted from 0 to F. In base 16 we need 16 different symbols, decimal numbers 10 through 15 are represented by letters A through F, respectively.

The  binary system (base 2) has only two symbols, '0' and '1'.

The following table shows the meaning of all the symbols in the hexadecimal  numbering system and their conversion to decimal or binary equivalents.

binary to hexadecimal conversion table 

To convert a value from hex to binary, you merely translate each hex symbol to the equivalent 4-bit binary group. For example, the hex number A5A5 translates into the binary 1010010110100101 equivalent. 

Solution 1. Conversion from hex to decimal, and then from decimal to binary

In Matlab, we can go from hexadecimal to decimal, and then, from decimal to binary. We can embed one instruction into the other, like this: 

bin_str = dec2bin(hex2dec(hex_str))

So, we can use this concept, like this:

hex_str = 'AF5'
bin_str = dec2bin(hex2dec(hex_str))

Matlab’s answer is: 

bin_str = 101011110101

It’s important to remember that both binary numbers and hexadecimal ones are treated as strings in Matlab.

Solution 2. Conversion using a Switch-Case structure

Now, let’s say that we want to explore how the hex characters are separated to form the binary symbols and how we can manipulate our own strings (binary and hexadecimal). 

We can develop a function to translate the table shown before. Our proposed method uses a switch-case structure.

% Hex to binary conversion
function b = h2b(h)
switch h
case {'0'}
        b =
case {'1'}
        b =
case {'2'}
        b =
case {'3'}
        b =
case {'4'}
        b =
case {'5'}
        b =
case {'6'}
        b =
case {'7'}
        b =
case {'8'}
        b =
case {'9'}
        b =
case {'A', 'a'}
        b =
case {'B', 'b'}
        b =
case {'C', 'c'}
        b =
case {'D', 'd'}
        b =
case {'E', 'e'}
        b =
case {'F', 'f'}
        b =

Now, we have to call the function for every hex character in the string, to convert each to a 4-bit binary number. One possible solution to separate the hex characters into 4-bit groups is shown here:

hex_str = input(
'Enter hexadecimal number: ', 's');
n = length(hex_str); 

bin_str = '';
for h = 1 : n
    bin_str = [bin_str h2b(hex_str(h))

Let’s try this routine. 

Enter hexadecimal number: af50
bin_str = 1010111101010000

Enter hexadecimal number: 15A7
bin_str = 1010110100111

 From 'Hex to binary' to home

 From 'Hex to binary' to 'Matlab Programming'
Binary to Hex conversions

Binary to decimal

Decimal to binary

Gray code


footer for hex to binary conversion page