How can I store binary strings into an array?

93 ビュー (過去 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 Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by