Reputation: 867
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?
Upvotes: 0
Views: 1803
Reputation: 104514
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
Upvotes: 4
Reputation: 16801
Try:
A = num2str(binary_vector,'%d')
or
A = sprintf('%d',binary_vector);
A = 101010101010101010101010
Upvotes: 1