Info
此问题已关闭。 请重新打开它进行编辑或回答。
fwrite ascii output error
1 次查看(过去 30 天)
显示 更早的评论
Hi all,
When writing data to a file in binary format using fwrite(), in some instances I get the hex output and in some I get the ASCII output.
Example code to show the error is as below;
% data arrays
dataArr1 = [-1 1];
dataArr2 = [-1 -1];
% open file
fid1 = fopen('test1.dat', 'w');
fid2 = fopen('test2.dat', 'w');
% write data to file
fwrite(fid1, dataArr1, 'int16');
fwrite(fid2, dataArr2, 'int16');
% close file
fclose(fid1);
fclose(fid2);
In this case test1.dat shows the expected output of 'ffff 0100' whereas test2.dat results in 'ÿÿÿÿ' rather than the expected 'ffff ffff'.
Any ideas why it outputs hex in one instance but ASCII in the other?
Thanks in advance!
*EDIT - I'm checking the values by opening the files in basic editor (Sublime)
1 个评论
dpb
2021-10-21
" I'm checking the values by opening the files in basic editor (Sublime)"
Well, it simply isn't the tool for the job -- it doesn't know how to handle non-printing ASCII characters (as most text editors don't).
I've played with it some in the past, but don't have installed at the moment; nothing in the doc's or the description at their web site gives any hint that it has a hex display mode.
Why are you doing this and what else would you expect?
采纳的回答
更多回答(1 个)
dpb
2021-10-21
I see no such thing...
>> fid=fopen('test2.dat');
fread(fid,'*int16')
fid=fclose(fid);
ans =
2×1 int16 column vector
-1
-1
>>
You do have to read the file in a manner consistent with that in which it was written, however.
You did not show us how you came to the above conclusion...most likely given the symptoms by
>> type test2.dat
ÿÿÿÿ
>>
which treats a stream (binary) file as ASCII...you'll get something similar with the other file as well, of course, but the character CHAR(1) isn't displayable in the browser.
Just looking at the bytes written one sees precisely what one expects to have been written was
>> fid=fopen('test1.dat');fread(fid),fid=fclose(fid);
ans =
255
255
1
0
>> fid=fopen('test2.dat');fread(fid),fid=fclose(fid);
ans =
255
255
255
255
>>
6 个评论
dpb
2021-10-21
There's nothing wrong with Sublime, either.
CHAR(1) and CHAR(-1) are simply not ASCII printing characters and therefore aren't displayed as such in ANY text-based tool.
As noted,I don't have Sublime itself installed (I had a machine crash and hadn't used it in favor of other programming editors so hadn't reinstalled it yet; doubt that will) so I can't go poke at the files you generated with it directly, but I have no doubt it will show exactly the hex bytes that are in the file if you use it as intended.
此问题已关闭。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!