Clear Filters
Clear Filters

I'm new to MATLAB and I'm trying to convert the text in a .txt file to binary digits ( 0's and 1's ). How do I do it ?

3 views (last 30 days)
converting_texttobinary = text2bin('encryptedMes.txt');
disp(converting_texttobinary)
I created a .txt file and tried to convert the text in the textfile to binary digits by using the method 'text2bin'. But my code doesn't seem to run. Can you please help me with it. Thank you.

Accepted Answer

Walter Roberson
Walter Roberson on 27 Jul 2022
  2 Comments
Vaibav Reddy
Vaibav Reddy on 27 Jul 2022
I've seen the code that you've sent. But I have one question regarding that code.
binS = dec2bin(text,8);
binS = binS';
binS = binS(:)';
binV = binS-48;
end
What does this part of the code do ?
Walter Roberson
Walter Roberson on 27 Jul 2022
decbin() take the numeric value that encodes each character and converts it to binary, with a minimum of 8 bits per entry. The output is arranged in rows, first row corresponding to text(1,1), second to text(2,1) and so on, heading down columns in MATLAB's standard "linear order". You will not get something like
'00101101' '00100110' ...
only something like
'00101101'
'00100110'
The next line transposes this from rows into columns. Instead of having 8 columns and as many rows as was there were characters in the text, you end up with 8 rows, and as many columns as there were characters in the text.
The line after that uses (:) to reshape the 8 x N matrix into a single column in linear order; that result is then transposed to make a row.
To illustrate the pattern,
a1 a2 a3 a4 a5 a6 a7 a8
b1 b2 b3 b4 b5 b6 b7 b8
got transposed to
a1 b1
a2 b2
a3 b3
a4 b4
a5 b5
a6 b6
a7 b7
a8 b8
and then the (:) rearranges to
a1
a2
a3
a4
a5
a6
a7
a8
b1
b2
b3
b4
b5
b6
b7
b8
and that gets transposed to
a1 a2 a3 a4 a5 a6 a7 a8 b1 b2 b3 b4 b5 b6 b7 b8
so after the end of the binS = binS(:)'; what we have is a row vector of bits in consecutive order, most significant bit of the text(1,1) first, then the second most significant bit, through to the least significant bit of text(1,1), then the most significant bit of text(2,1) through to the least significatn bit of text(2,1) and so on. It is a bit stream.
It is, however, at this point still character data -- still the characters '0' and '1' not numeric 0 and 1.
The
binV = binS-48;
subtracts 48 from the character encoding. The character encoding for the "letter" '0' is 48 and for the "letter" '1' is 49, so when you subtract 48 from '0' you get numeric 0 instead of character '0' and when you subtract 48 from '1' you get numeric 1 instead of character '1'.

Sign in to comment.

More Answers (0)

Categories

Find more on Convert Image Type 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!