Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 244
HH. Avatar asked Dec 06 '22 04:12

HH.


1 Answers

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.

like image 80
gnovice Avatar answered Jan 17 '23 16:01

gnovice