How to convert binary to decimal without using a loop?

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

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.

+4
source share
3 answers

Note. This answer mainly refers to unsigned data types. To convert to signed types, you need to follow a few additional steps, which are discussed here .


The bin2dec function is one of the options, but it requires you to change the vector to a string first. bin2dec can also be slow compared to calculating the number yourself. Here is a solution that is 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 elementwise by a vector of degrees 2 with exponents ranging from numel(A)-1 to 0 . The resulting vector is then summed to get an integer represented by a binary pattern of zeros and ones, with the first element in the array counting as 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 from MATLAB by using find to get their indices (avoiding elementwise multiplication and potentially reducing the number of exponential 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 


Expanding matrix solution ...

If you have many binary vectors that you want to convert to integers, the solution above can be easily changed to convert all values ​​with a single matrix operation. Suppose A is an N-by -1 2 matrix, with one binary vector per row. The following converts them all to an N-by -1 integer value vector:

 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

+10
source

Dominic replies that you have access to the Data Acquisition toolbar. If you do not use bin2dec :

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

or (in reverse order)

 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 bits 1 and 12!

+4
source

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

Try:

 binvec2dec(A) 

The conclusion should be:

  ans = 774 

If the MSB remains the largest, first use fliplr(A) .

+2
source

All Articles