is there a way to make "short" variable in matlab?
조회 수: 10 (최근 30일)
이전 댓글 표시
I'm using some code to read a file
The file goes like this:
D8 00 EA 00
the real values goes like this:
-40, -22
but if I read to code like this it doesn't work
for n=0:9999
n
filename = sprintf(filename_format,n);
fileID=fopen(filename,'r');
for i=1:784
z(n+1,i)=fread(fileID,1,'int16');
end
fclose(fileID);
end
end
it would return 218 234
댓글 수: 1
Rik
2022년 9월 12일
I would have expected this to work. As a workaround you could try reading it as uint16 and then using cast or typecast (I always forget which one doesn't change the underlying data). I'm on mobile so I can't easily test code for you.
채택된 답변
Walter Roberson
2022년 9월 12일
The file goes like this: D8 00 EA 00 the real values goes like this: 40, -22
You are expecting two values, not 4 values, and you talk about "short" and you talk about "int16". So D8 00 and EA 00 are each byte pairs for one 16 bit value.
Consider D8 00. Is that D8 as the most signicant bits and 00 as the least significant bits, also known as "big-endian" order? If so then the value should be uint16(0xD8 * 256 + 0x00) and typecast the 16 bits to signed instead of unsigned. But that is not the representation of -40: the representation of -40 is 0xFF 0xD8.
Or is D8 the least significant bits and 00 the most significant bits, also known as "little-endian" order, which is the default order on MATLAB these days> If so then the value should be uint16(0x00 * 256 + 0xD8) and typecast the 16 bits to unsigned. But 0x00d8 is just plain 216 not -40 since the leading bits are 0.
So you have to decide whether the value is -10240 (0xD800) or if the value is 216 (0x00D8), or if each byte encodes an 8 bit signed integer but you want to skip the even-numbered bytes.
%prepare file
data = uint8([0xd8, 0x00, 0xea, 0x00])
filename = tempname + ".txt";
fid = fopen(filename, 'w');
bytes = fwrite(fid, data, 'uint8')
fclose(fid)
%read it back
fid = fopen(filename, 'r', 'ieee-be');
z = fread(fid, [1 inf], '*int16')
fclose(fid);
z
dec2hex(z)
댓글 수: 2
Walter Roberson
2022년 9월 15일
I already gave you the algorithm at https://www.mathworks.com/matlabcentral/answers/1793380-is-there-a-way-to-read-16bit-float-mantissa-8bit-bin-file#answer_1046915
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Low-Level File I/O에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!