A function that converts a binary string to its corresponding char values.
27 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
nishant sharma
am 31 Mär. 2015
Bearbeitet: Stephen23
am 31 Mär. 2015
I need to create a function that converts a binary string to its corresponding char values. I have create a function to convert char values to binary string. Now i need its reverse. Code for str to binary is given here.
Function [y] = str2bin(txt)
For i=1:length(txt)
m=txt(i);
y(i, :) = dec2bin(double(m));
End
0 Kommentare
Akzeptierte Antwort
Stephen23
am 31 Mär. 2015
Bearbeitet: Stephen23
am 31 Mär. 2015
Rather than doing this in a loop you should learn how to write vectorized code in MATLAB. Vectorized code is neater, faster and much easier to read. Loops are your second choice, not your first choice.
>> str = 'hello world!';
>> dec2bin(str)
ans =
1101000
1100101
1101100
1101100
1101111
0100000
1110111
1101111
1110010
1101100
1100100
0100001
which returns a character array. If you want a cell array of strings, simply wrap this in a num2cell call:
>> out = num2cell(dec2bin(str),2)
out =
'1101000'
'1100101'
'1101100'
'1101100'
'1101111'
'0100000'
'1110111'
'1101111'
'1110010'
'1101100'
'1100100'
'0100001'
>> bin2dec(out)
ans =
104
101
108
108
111
32
119
111
114
108
100
33
Or if you want the original string instead:
>> char(bin2dec(out).')
ans = 'hello world!'
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!