Split binary number into individual bytes

Hello,
I want to convert a list of binary numbers into 3 different numbers. Each binary number is of 21 bits and I want to convert it into 3 sets of [22:12 11:1 0].
Example is shown below.
00111001110101000101011 => 00111001110 10100010101 1
Below is a sample of the file
00111001110101000101011
00111001110101000101001
00111001110101000100111
00111001110101000100101
00111001101101000100011
00111001101101000100001
00111001101101000011111
00111001101101000011101
00111001101101000011011
00111001101101000011001
I have used the following approach but to no avail as it keeps reading data in double format.
close all
clear all
clc
load D:\Folder\File.txt
dataorig=File;
N=length(dataorig)
finalMat=ones(N,3);
datastr=string(dataorig);
temp=char(datastr(1))
num1=temp(1:11)

 採用された回答

Alex Mcaulley
Alex Mcaulley 2019 年 4 月 26 日
編集済み: Alex Mcaulley 2019 年 4 月 26 日

0 投票

This approach save the result in a cell array:
fid = fopen('File.txt');
data = textscan(fid,'%s');
fclose(fid);
dataNew = cellfun(@myfun,data{1,1},'UniformOutput',false);
dataNew = vertcat(dataNew{:});
%To save in a new file
fid = fopen('example.txt','w');
dataNew = dataNew';
fprintf(fid,'%s\t%s\t%s\r\n',dataNew{:});
fclose(fid);
function b = myfun(a)
a = flip(a);
b = {a(1:11),a(12:22),a(end)};
end

4 件のコメント

Usman Siddique
Usman Siddique 2019 年 4 月 26 日
I have run the your code bt i cant seem to find any outputs
Can you please explain what have you done in the 4th line of code i.e.
dataNew = cellfun(@myfun,data{1,1},'UniformOutput',false);
Also, shouldn't the function "myfun" be a separate file.
Alex Mcaulley
Alex Mcaulley 2019 年 4 月 26 日
Can you upload your txt file? Are you getting any error? This code works for me just putting your sample in a txt file.
dataNew = cellfun(@myfun,data{1,1},'UniformOutput',false); %This line executes the function myfun for each row of your txt file and save the results in a cell array
The function myfun should be defined at the end of your function/script
Usman Siddique
Usman Siddique 2019 年 4 月 26 日
I have run the code. As you mentioned it saves the result in a cell. The problem is I cant seem to view it as text in the command window. It displays "{1×3 cell}" for every ith row.
Is there any way to store the results in a separate text file?
Alex Mcaulley
Alex Mcaulley 2019 年 4 月 26 日
To see the result in the command window, just use:
dataNew = vertcat(dataNew{:})
To write the result in a new txt file:
fid = fopen('example.txt','w');
dataNew = dataNew';
fprintf(fid,'%s\t%s\t%s\r\n',dataNew{:});
fclose(fid);
I have edited my first answer to show the full code

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeText Data Preparation についてさらに検索

製品

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by