Binary to Hexadecimal Conversion in MATLAB

This article provides MATLAB source code for converting binary data to hexadecimal representation.

MATLAB Code

% function [hexa] = bin2hexa(binvect)
binvect = [1 0 1 0 1 0 1 0 1 0 0 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 1 0];
leng    = length(binvect);
hexa    = [];

for p = 1:leng/4
  hexa = [hexa sum(2.^[3 2 1 0] .* binvect((p-1)*4+[1:4]))];
end

hex  = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
hexa = hex(hexa+1);

Input and Output

The following image illustrates the input and output relationship for the binary to hexadecimal conversion.

Binary to Hex Input Output

Image alt: Binary to Hex

Explanation

The MATLAB code takes a binary vector as input and processes it in chunks of 4 bits. Each 4-bit chunk is converted to its equivalent decimal value (0-15), and then this decimal value is used as an index to retrieve the corresponding hexadecimal character from the hex array.

The conversion is performed using the following steps:

  1. Initialization: The input binary vector binvect is defined. Its length leng is calculated and an empty vector hexa is initialized to store the resulting hexadecimal values.

  2. Iteration: The code iterates through the binary vector, processing it in groups of 4 bits.

  3. Decimal Conversion: Inside the loop, the sum(2.^[3 2 1 0] .* binvect((p-1)*4+[1:4])) part calculates the decimal equivalent of each 4-bit chunk. It multiplies each bit by the corresponding power of 2 (8, 4, 2, 1) and sums the results. For example, if the 4-bit chunk is [1 0 1 0], the calculation would be:

    (123)+(022)+(121)+(020)=8+0+2+0=10(1 * 2^3) + (0 * 2^2) + (1 * 2^1) + (0 * 2^0) = 8 + 0 + 2 + 0 = 10

  4. Hexadecimal Conversion: The calculated decimal value (0-15) is then used as an index to access the hex character array. Since MATLAB array indices start from 1, 1 is added to the decimal value. So, a decimal value of 10 would access hex(11), which is ‘a’.

  5. Concatenation: The resulting hexadecimal character is appended to the hexa vector.

  6. Output: Finally, the hexa vector, containing the hexadecimal representation of the input binary data, is returned.