How can I store binary strings into an array?

119 次查看(过去 30 天)
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