Search code examples
arraysmatlabbinaryhexcell-array

Converting Hex to Decimal and merging the result into one cell in matlab


I have the following hex values:

 a = '55 D1 1F 81'; 
 b = '9A D2 1F 81'; 
 c = 'EF D3 1F 81'; 
 d = '79 D4 1F 81';

and I wish to convert them into binary and then to decimal. the way I would like the result is as shown below.

enter image description here

I also have written a code. However it does not give me the required result.

It converts the data into binary but flips the binary values and then messes up the final decimal result.

Here is the code:

 a = '55 D1 1F 81'; 
 b = '9A D2 1F 81'; 
 c = 'EF D3 1F 81'; 
 d = '79 D4 1F 81';


s = {a;b;c;d};

%s = cellfun(@strsplit, s, 'UniformOutput', false);
s = regexp(s,'(\w)','match');    
s = vertcat(s{:});
%s = fliplr(s);

% Iterate over each row
for rowNum = 1:size(s,1)

    % To build up binary string from left to right
    binaryString = [];

    % Iterate over each column
    for colNum = 1:size(s,2)

        % Convert hex -> dec -> 8-bit binary word        
        outputBin = dec2bin(hex2dec(s{rowNum,end+1-colNum}), 4);
        binaryString = [binaryString, outputBin]; 

        % Save solution to output array:
        outputBinary{rowNum, colNum} = binaryString;
        outputDec(rowNum, colNum) = bin2dec(binaryString);
    end
end

Can anybody please help me in fixing this problem?


Solution

  • You can use the following function:

    function C = HDB(s) %Hex Dec Bin
       s   = regexp(s,'(\w)','match'); 
       c1  = flip([s{:}].');
       len = 1:length(c1);
    
       hex   = arrayfun(@(x) c1(1:x).',len,'UniformOutput',0)
       C.hex = arrayfun(@(x) flip(hex{x}),len,'UniformOutput',0)
       C.dec = arrayfun(@(x) hex2dec(C.hex{x}),len,'UniformOutput',0)
       C.bin = arrayfun(@(x) dec2bin(C.dec{x}),len,'UniformOutput',0)
    end
    

    For example for you array a you can use:

    C = HDB(a)
    

    OUTPUT:

    hex = 
    {
      [1,1] = 1
      [1,2] = 81
      [1,3] = F81
      [1,4] = 1F81
      [1,5] = 11F81
      [1,6] = D11F81
      [1,7] = 5D11F81
      [1,8] = 55D11F81
    }
    dec = 
    {
      [1,1] =  1
      [1,2] =  129
      [1,3] =  3969
      [1,4] =  8065
      [1,5] =  73601
      [1,6] =  13705089
      [1,7] =  97591169
      [1,8] =  1.4398e+09
    }
    bin = 
    {
      [1,1] = 1
      [1,2] = 10000001
      [1,3] = 111110000001
      [1,4] = 1111110000001
      [1,5] = 10001111110000001
      [1,6] = 110100010001111110000001
      [1,7] = 101110100010001111110000001
      [1,8] = 1010101110100010001111110000001
    }