在每个字节后添加空格到二进制文件

时间:2014-07-14 14:12:03

标签: image matlab binary byte whitespace

我有一个图像的二进制文件,它是256x256数组 我只想在此文件中的每个字节后添加一个空格 例如 000101010101110101010100
预期输出: 00010101 01011101 01010100
可以任何人建议我使用matlab prefarably

3 个答案:

答案 0 :(得分:1)

如果您已经以char数组的形式拥有那些0/1值,例如

a =
101001011111011101010100
100101001010100000111111
100100100001011110110101
001010011111110000001010

你可以这样做:

n = 8; %// byte size
b = a(:,ceil(n/(n+1):n/(n+1):end)); %// repeat every n-th position
b(:,n+1:n+1:end) = ' '; %// replace those repeated positions by spaces

给出了

b =
10100101 11110111 01010100 
10010100 10101000 00111111 
10010010 00010111 10110101 
00101001 11111100 00001010 

答案 1 :(得分:0)

...要获取Luis Mendo提到的字符数组,您可以执行以下操作:

%edge length of image
edge = 256;

%open and read file
fid = fopen('imageData.txt');
C = fread(fid,[edge+2,edge]);

+2实际上取决于您的文件,它是否包含回车符?如果没有,请将其留下。

% get char array
chararray = char(C(1:edge,:)');

然后我将继续如下:

wordlength = 8;
cellarray = mat2cell(chararray,ones(1,edge),wordlength*ones(1,edge/wordlength));
cellarray = cellfun(@(x) [x ' '],cellarray,'uni',0);
output = cell2mat(cellarray);
%// remove last column with unwanted space
output = output(:,end-1:end)

并将其再次写入文件。


关于你的评论,试试这个:

wordlength = 8;
cellarray = mat2cell(chararray,ones(1,edge),wordlength*ones(1,edge/wordlength));
fid2 = fopen( yourFilepath ,'w');
fprintf(fid2 , '%s\r\n', cellarray {:});
fclose(fid2);

答案 2 :(得分:0)

你可以用一个简单的Perl单线程来做到这一点:

perl -e '$/=\1;while(<>){print $_," ";}' < yourFile > newfile

$/=\1设置记录分隔符,因此我们一次读取一个字节。然后我们进入一个循环读取一个字节,打印出来,然后是一个空格直到文件结束。