How can I store binary strings into an array?

조회 수: 115 (최근 30일)
jec
jec 2017년 7월 22일
답변: Joseph Hall 2021년 8월 27일
I have a character string that I converted into a ASCII format. But I don't know how will I put the individual numbers into an array. For example I have a character string that I've extracted in a text file (which contains 'dog' in this case). I converted it into ASCII using:
fid = fopen('sample.txt', 'r');
Data = fread(fid);
CharData = char(Data);
fclose(fid);
ascii = dec2bin(CharData)
this yielded:
ascii =
1100100
1101111
1100111
Now I want to store each binary per word into separate arrays which would look like this:
[1, 1, 0, 0, 1, 0, 0]
[1, 1, 0, 1, 1, 1, 1]
[1, 1, 0, 0, 1, 1, 1]
...or, if possible, each bit into a matrix
this will vary depending on the length of the string. But what happens is when I use the following code:
ascii = dec2bin(CharData);
out = str2num(ascii')'
It yields:
out = 111 111 0 10 111 11 11

답변 (2개)

Joseph Hall
Joseph Hall 2021년 8월 27일
Use: dec2bin(CharData)=='1'
Here is an example:
binaryDataAsCharArray = dec2bin(randi(2^7-1,1,3),7)
binaryDataAsCharArray = 3×7 char array
'1100110' '1011000' '0000001'
binaryDataAsLogicalArray = binaryDataAsCharArray=='1'
binaryDataAsLogicalArray = 3×7 logical array
1 1 0 0 1 1 0 1 0 1 1 0 0 0 0 0 0 0 0 0 1

Walter Roberson
Walter Roberson 2017년 7월 22일
ascii = dec2bin(CharData, 8) - '0';
ascii_cell = num2cell(ascii, 2);
[d, o, g] = deal(ascii_cell{:});
However, what if the length of the string changes? Which variables should be used?
if length(CharData) == 1
d = deal(ascii_cell{:});
elseif length(CharData) == 2
[d, o] = deal(ascii_cell{:});
elseif length(CharData) == 3
[d, o, g] = deal(ascii_cell{:});
elseif ....
end
This is clearly not good code, and clearly you would run out of variables.
Don't even think about dynamically creating new variable names according to the length. Just leave the data in the cell array (at most) or in the 2D numeric array (better)
If you want to reconstruct from a 2D numeric array like the one I construct above, then the technique is
reconstructed = bin2dec( char(ascii + '0') );
  댓글 수: 1
Walter Roberson
Walter Roberson 2017년 7월 22일
"...or, if possible, each bit into a matrix"
clearvars -regexp B_*
ascii = dec2bin(CharData, 8);
nrow = size(ascii, 1);
for K = 1 : nrow
for C = 1 : 8
thisvarname = sprintf('B_%d_%d', K, C);
thisval = ascii(K,C);
eval( [thisvarname, '=', thisval;] );
end
end
Each bit will be placed into a separate matrix, such as B_1_3 and B_19_8 . Now what are you going to do with these separate matrices?

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

카테고리

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