Info
この質問は閉じられています。 編集または回答するには再度開いてください。
fwrite ascii output error
3 ビュー (過去 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!