ASCII string for binary vector in MATLAB?

How to convert a string in MATLAB to a binary ASCII representation vector of this string?

For example, I want to convert

string = 'Mary had a little lamb'; 

so that the vector looks like this:

 [0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1, etc.] \-------v------/ \-------v------/ M a 
+4
source share
2 answers

Do you want array entries 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:

 >> 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 
+4
source

It's pretty simple, but you should know that MATLAB internally saves a string in ASCII and can calculate with the corresponding numeric values.

So, first we convert each character (number) into a binary extension (length 8) and, finally, combine all these cells together with your desired result.

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

edit:. Oli Charlesworth mentions this below, the same thing can be done with the following code:

 reshape(dec2bin(str, 8)', 1, []) 
+2
source

All Articles