is there a way to make "short" variable in matlab?
10 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Won Geun Shin
le 12 Sep 2022
Commenté : Walter Roberson
le 15 Sep 2022
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 commentaire
Rik
le 12 Sep 2022
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.
Réponse acceptée
Walter Roberson
le 12 Sep 2022
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 commentaires
Walter Roberson
le 15 Sep 2022
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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Low-Level File I/O dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!