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
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
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])
data = 1×4
216 0 234 0
filename = tempname + ".txt";
fid = fopen(filename, 'w');
bytes = fwrite(fid, data, 'uint8')
bytes = 4
fclose(fid)
ans = 0
%read it back
fid = fopen(filename, 'r', 'ieee-be');
z = fread(fid, [1 inf], '*int16')
z = 1×2
-10240 -5632
fclose(fid);
z
z = 1×2
-10240 -5632
dec2hex(z)
ans = 2×4 char array
'D800' 'EA00'
  2 个评论
Won Geun Shin
Won Geun Shin 2022-9-15
I was hoping it to be a floating point that goes 1 sign bit and 7 bit of integer and 8 bit of decimal
example is here:
ex]
01000110.11000000 = 70.75 (70+0.75(0.5+0.25))
10111001.01000000 = -70.75(-71+0.25)
Walter Roberson
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 CenterFile 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!

Translated by