How can I store binary strings into an array?
88 views (last 30 days)
Show older comments
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
0 Comments
Answers (2)
Joseph Hall
on 27 Aug 2021
Use: dec2bin(CharData)=='1'
Here is an example:
binaryDataAsCharArray = dec2bin(randi(2^7-1,1,3),7)
binaryDataAsLogicalArray = binaryDataAsCharArray=='1'
0 Comments
Walter Roberson
on 22 Jul 2017
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 Comment
Walter Roberson
on 22 Jul 2017
"...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?
See Also
Categories
Find more on Characters and Strings 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!