Clear Filters
Clear Filters

How i can convert a text into binary and then split the binary form, finally convert each partition into ASCII code?

8 views (last 30 days)
Hello matlab community.
Sorry friends, I am a beginner with Matlab
I have a problem in this code, which is when i run this code for text file with small size , the time is very large. can any one help me to faster the running of this code?? is this code is true ?
fd=fopen('path\filename.txt'); % when the size of text file are 20 kilo bytes, it take about 30 minutes
format='%c';
Entered_Text = fscanf(fd,format);
Text_ascii = unicode2native(Entered_Text,'utf-8'); % Convert each character of a text into 8 bits ASCII code
for i = 1 : length(Text_ascii)
Binary_text{i} = dec2bin(Text_ascii(i),8); % Convert 8 bits ASCII code of a text into binary
out{1,i} = mat2cell(Binary_text{i},1,[2,2,2,2]); % Divide each Byte from (Binary_text) into four parts(each part two bits)
result = horzcat(out{:}); % Store the result of partitioned (Binary_text) into cell vector
Final_result = cellfun(@bin2dec, result); % Convert the result of each two bits into ASCII code
end

Accepted Answer

Voss
Voss on 28 Nov 2022
Edited: Voss on 28 Nov 2022
You can replace your for loop with this, which will be faster because it calls dec2bin one time on the entire text instead of one time per character, and it avoids converting to and from cell arrays and uses indexing instead:
Binary_text = dec2bin(Text_ascii,8);
Final_result = zeros(numel(Text_ascii),4);
for ii = 1:4
Final_result(:,ii) = bin2dec(Binary_text(:,(ii-1)*2+[1 2]));
end
This Final_result contains the result for all of the characters in Text_ascii, with each row corresponding to a single character.

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!