Bjarke Freund-Hansen
Bjarke Freund-Hansen

Reputation: 30144

ASCII string to binary vector in MATLAB?

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         

Upvotes: 4

Views: 16318

Answers (2)

stardt
stardt

Reputation: 1219

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

Upvotes: 5

Egon
Egon

Reputation: 4787

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, [])

Upvotes: 2

Related Questions