1

Possible Duplicate:
Converting binary to decimal without using loop

I'm looking for the simplest and fastest solution. I tried documentation but could find anything.

I have an array of bits like [0, 1, 1, 1] and I want to convert it to simple int number 7. I get this array with bitget(x, 1:3), where x is an integer.

Community
  • 1
  • 1
tadasz
  • 4,366
  • 5
  • 26
  • 33
  • Technically this could be interpreted as a slightly different question than 1552966 because one could interpret this question as how to get a number from a bit range of x, to which I would answer use a bit mask and bit shift – Jimbo Jul 01 '17 at 23:42

3 Answers3

10

Just as a pedagogical alternative to @Edwin and @Azim's solution's (which are better for production), try

b = [1 0 0 1]; % or whatever
sum(b.*(2.^[length(b)-1 : -1 : 0])) % => 9 for the above

We create the basis elements with 2.^[length(b)-1 : -1 : 0] = [8 4 2 1], multiply each element by the binary value to get [8 0 0 1], then sum to get the final answer.

dantswain
  • 5,427
  • 1
  • 29
  • 37
4

@Edwin's answer uses binvec2dec which is part of the Data Acquisition Toolbox. This toobox is an additional toolbox (developed by Mathworks) but not part of the base MATLAB package.

Here is a solution that does not depend on this toolbox.

  1. Use num2str to convert the binary array to a string

    str=num2str(bin_vec);

  2. use bin2dec to get decimal value

    dec_num=bin2dec(str);

Azim J
  • 8,260
  • 7
  • 38
  • 61
  • External huh? Oh well, it HAS been quite a while since I've worked with Matlab, and I don't even know why I'm trying to work with it again. That said, if the asker is serious about developing in Matlab, there's no harm in using external library, especially when they're provided by the language maker and not an external 3rd party. – Edwin Dec 07 '11 at 22:46
  • @Edwin the basic MATLAB package does not include any of the extra toolbox like the DAQ toolbox. Maybe I should say extra (changed wording) – Azim J Dec 07 '11 at 22:50
  • External in the sense that it does not ship with Matlab and you have to pay extra for it. – mbatchkarov Dec 07 '11 at 22:50
  • @reseter Oh...I was unaware of that. – Edwin Dec 07 '11 at 22:52
1

A little rusty on Matlab, but this should work.

% This assumes you're using a vector of dimension 1 x n (i.e. horizontal vector)
% Otherwise, use flipud instead of fliplr
function [dec_num] = convert(bin_vec)
bin_vec = fliplr(bin_vec);
dec_num = binvec2dec(bin_vec);

% EDIT: This should still work
num = convert(bitget(x, 1:3);

For future reference, if this is about homework, use the homework tag.

binvec2dec Documentation
fliplr Documentation
flipud Documentation

Edwin
  • 2,074
  • 1
  • 21
  • 40