tags:

views:

493

answers:

3

Hi,

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

E.g. A = [0,1,1,0,0,0,0,0,1,1,0,0];

Bit 1 is the MSB, Bit 12 is the LSB .

How do I do it?

+1  A: 

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.

Dominic Rodger
+2  A: 

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!

Amro
+2  A: 

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

EDIT: In addition, 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.

gnovice
This is somewhat similar to what **bin2dec** function does except using **pow2**, in addition to removing spaces from string and converting it to number using `s-'0'`
Amro

related questions