How can I convert a binary to a decimal without using a loop?

11,145

Solution 1

Note: This answer applies primarily to unsigned data types. For converting to signed types, a few extra steps are necessary, discussed here.


The bin2dec function is one option, but requires you to change the vector to a string first. bin2dec can also be slow compared to computing the number yourself. Here's a solution that's about 75 times faster:

>> A = [0,1,1,0,0,0,0,0,1,1,0,0];
>> B = sum(A.*2.^(numel(A)-1:-1:0))

B =

        1548

To explain, A is multiplied element-wise by a vector of powers of 2, with the exponents ranging from numel(A)-1 down to 0. The resulting vector is then summed to give the integer represented by the binary pattern of zeroes and ones, with the first element in the array being considered the most significant bit. If you want the first element to be considered the least significant bit, you can do the following:

>> B = sum(A.*2.^(0:numel(A)-1))

B =

        774

Update: You may be able to squeeze even a little more speed out of MATLAB by using find to get the indices of the ones (avoiding the element-wise multiplication and potentially reducing the number of exponent calculations needed) and using the pow2 function instead of 2.^...:

B = sum(pow2(find(flip(A))-1));  % Most significant bit first
B = sum(pow2(find(A)-1));        % Least significant bit first


Extending the solution to matrices...

If you have a lot of binary vectors you want to convert to integers, the above solution can easily be modified to convert all the values with one matrix operation. Suppose A is an N-by-12 matrix, with one binary vector per row. The following will convert them all to an N-by-1 vector of integer values:

B = A*(2.^(size(A, 2)-1:-1:0)).';  % Most significant bit first
B = A*(2.^(0:size(A, 2)-1)).';     % Least significant bit first

Also note that all of the above solutions automatically determine the number of bits in your vector by looking at the number of columns in A.

Solution 2

Dominic's answer assumes you have access to the Data Acquisition toolbox. If not use bin2dec:

A = [0,1,1,0,0,0,0,0,1,1,0,0];
bin2dec( sprintf('%d',A) )

or (in reverse)

A = [0,1,1,0,0,0,0,0,1,1,0,0];
bin2dec( sprintf('%d',A(end:-1:1)) )

depending on what you intend to be bit 1 and 12!

Solution 3

If the MSB is right-most (I'm not sure what you mean by Bit 1, sorry if that seems stupid):

Try:

binvec2dec(A)

Output should be:

 ans =
   774

If the MSB is left-most, use fliplr(A) first.

Share:
11,145
HH.
Author by

HH.

Updated on July 12, 2022

Comments

  • HH.
    HH. almost 2 years

    I have a 12-bit binary that I need to convert to a decimal. For example:

    A = [0,1,1,0,0,0,0,0,1,1,0,0];
    

    Bit 1 is the most significant bit, Bit 12 is the least significant bit.