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.

1
  • 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 Commented Jul 1, 2017 at 23:42

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

4 Comments

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 the basic MATLAB package does not include any of the extra toolbox like the DAQ toolbox. Maybe I should say extra (changed wording)
External in the sense that it does not ship with Matlab and you have to pay extra for it.
@reseter Oh...I was unaware of that.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.