0

I would like to convert a binary vector of 24 bits to a single string.

For example, I should get the string: '101010101010101010101010' from this vector: [1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0]

I tried this :

binary_vector = [1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0];
A = num2str(binary_vector);
l = length(A);

And I obtain :

A =

1  0  1  0  1  0  1  0  1  0  1  0  1  0  1  0  1  0  1  0  1  0  1  0


l =

    70

What I don't understand is why my length of A is 70? Shouldn't be 24?

2 Answers 2

4

That's because you are also including spaces in the final result. beaker in his answer above suggested the proper way to do it using a format specifier with num2str or sprintf. However, if your string just consists of 0/1, another method I can suggest is to add 48 to all of your numbers, then cast with char:

A = char(binary_vector + 48);

The ASCII code for 0 and 1 is 48 and 49 respectively, so if you add 48 to all of the numbers, then use char, you would be representing each number as their ASCII equivalents, thus converting your number to a string of 0/1.

Something more readable can be:

A = char(binary_vector + '0');

The '0' gets coalesced into its equivalent double value, which is 48 as that is the ASCII code for 0. When you add something to a double, which is what binary_vector is - a vector of doubles, the type gets converted to its equivalent double type. It depends on your preference, but I use the first one out of habit because of code golfing.

We get:

>> A

A =

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

2 Comments

I don't understand why padding the columns isn't a documented behavior.
@excaza I really don't know either to be honest.
1

Try:

A = num2str(binary_vector,'%d')
or
A = sprintf('%d',binary_vector);

A = 101010101010101010101010

1 Comment

Great! I would have added an explanation as to why num2str adds 2 spaces, but to be honest, I have no idea why they did it that way.

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.