4

How do I convert a string in MATLAB to a binary vector of the ASCII representation of that string?

For example, I want to convert

string = 'Mary had a little lamb';

to a vector looking like:

[0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1, etc.]
\-------v------/ \-------v------/
        M                a         

2 Answers 2

5

Do you want the entries of the array to be numbers not characters? If yes, then this should work:

s = 'Mary had a little lamb';
a = dec2bin(s,8)';
a = a(:)'-'0'

Sample output showing what this does is:

>> s = 'Ma';          
>> a = dec2bin(s,8)'; 
>> class(a)
ans =
char
>> a = a(:)'-'0'      
a =
  Columns 1 through 13
     0     1     0     0     1     1     0     1     0     1     1     0     0
  Columns 14 through 16
     0     0     1
>> class(a)
ans =
double
Sign up to request clarification or add additional context in comments.

3 Comments

That would create a vector with the letters represented as their number in the alphabet, right? (Which is not what I want).
@bjarkef No, this creates a vector with doubles that are either 0 or 1. I have edited my response to show the output. The other answer creates a vector with chars, i.e. a string.
Great, looks exactly like what I am looking for then. :)
2

That's quite easy, but you have to know that MATLAB internally stores a string in ASCII and is able to compute with the corresponding numerical values.

So we first convert every character (number) to binary expansion (of length 8) and finally we concatenate all these cells together to your desired result.

x = arrayfun(@(x)(dec2bin(x,8)), string, 'UniformOutput', false)
x = [x{:}]

edit: As Oli Charlesworth mentions it below, the same can be done by following code:

reshape(dec2bin(str, 8)', 1, [])

3 Comments

Can't you just do reshape(dec2bin(str,8)', 1, [])?
@Oli Charlesworth: you can do that as well (I guess that might be a bit faster, also). I didn't know you could pass empty dimensions to reshape, which is why I hadn't given it any thought. So thank you for that!
@Egon: Do you have an example of the output corresponding to the example input string in my question?

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.