I would like to extract each character from a text file. Later convert each character(in ASCII) to binary and store the binary form in an array.

조회 수: 1 (최근 30일)
For example, text file: example.txt which contains text "hello, hi". It will take each character and convert it to binary and store the value in an array.

답변 (1개)

Guillaume
Guillaume 2016년 5월 4일
Note that computers store characters and numbers in binary form, so it's not clear what you mean by "convert it to binary".
In any case, to read the file:
content = fileread('C:\full\path to\example.txt');
If you want matlab to display the ASCII value (strictly speaking it's not ASCII as characters can be outside the range 0-127):
asciivalues = double(content);
If what you meant is that you want the individual bits of each character as separate elements of your array:
charbits = cell2mat(arrayfun(@(c) bitget(c, 8:-1:1), asciivalues, 'UniformOutput', false));
  댓글 수: 2
sb
sb 2016년 5월 4일
Thanks for the reply. Here I get a stream of binary bits combined of every character in the text file. But I need something like this:
for example: my text file contains "is"
i : 0 0 1 1 0 1 0 0 1
s : 0 0 1 1 1 0 0 1 1
I would like to have an array like this:
0 0 1 1 0 1 0 0 1
0 0 1 1 1 0 0 1 1
That is, I would like to have it in different rows.
Guillaume
Guillaume 2016년 5월 4일
Simply transpose the cell array returned by arrayfun before the call to cell2mat. That is:
charbits = cell2mat(arrayfun(@(c) bitget(c, 8:-1:1), asciivalues, 'UniformOutput', false)'); %note the '

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by