8

How could I convert array of digits to a binary number? For instance:

a=[1 0 1 0 1 0]

I would like to convert to a binary number

b=101010

Is it possible to do without loops?

1
  • Instead of using a string-representation to do whatever you want to do, you might want to check the functions bitget, bitset and the ones mentioned there under see also. I haven't seen a case yet, where working with the string-representation is really necessary, nevertheless people ask things like this all the time. Plus, working with strings is slower and eats more memory. Commented Oct 29, 2013 at 16:58

2 Answers 2

19

Maybe this is what you want:

char(a+'0')

Example:

>> a=[1 0 1 0 1 0]

a =

     1     0     1     0     1     0

>> char(a+'0')

ans =

101010

This works by converting each number to its ASCII code (+'0') and then converting the vector of resulting numbers to a string (char()).

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

3 Comments

To avoid to depend on the peculiarities of ASCII, an alternative would be bindig = '01'; bindig(a + 1).
And if speed is a concern, char(a+48) might be faster. (twice as fast in Octave)
@rayryeng Thanks! That +'0' thing (and -'0' for the way back) is yet another thing I learned in SO :-)
7

You can convert it to a string:

sprintf('%d',a)

which I think is the only alternative to an array of logicals.

2 Comments

Nice, but not the best alternative :)
@DanielR it's an overkill compared to char.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.