Effacer les filtres
Effacer les filtres

How to invert the function typecast?

4 vues (au cours des 30 derniers jours)
Dani Tormo
Dani Tormo le 20 Avr 2016
Commenté : Dani Tormo le 21 Avr 2016
Hello,
I am using typecast to convert from double to uint8 and store some data in a file:
fwrite(fid,typecast(double(data),'uint8'),'uint8');
Now, I want to read this data back, but if I use fread like this:
data2 = fread(fid, length(data), 'double');
when it finds a value equivalent to a new line (10) or carriage return (13) - I am not sure which one of those actually is - it corrupts the data read after that value.
How can I avoid this problem? I need to write the data using uint8 because I need to read it from an ARM, process it, write it back, and read it in Matlab.
I do not know if there is a better way of doing all this.
Thanks!
  3 commentaires
James Tursa
James Tursa le 20 Avr 2016
Modifié(e) : James Tursa le 20 Avr 2016
Please show all of your relevant code, including your fopen statements, what is the class and size of the variable data, all of your fwrite and fread statements, etc.
Dani Tormo
Dani Tormo le 20 Avr 2016
Modifié(e) : Dani Tormo le 20 Avr 2016
Writing the data into the SD card (data_array is a 10000x1 array in double-precision format):
fid = fopen('asdf.txt','wt');
fwrite(fid,typecast(data_array,'uint8'),'uint8');
fclose(fid);
Reading back the data from the SD card:
fid = fopen('asdf.txt','r');
data_array2 = fread(fid, length(data_array), 'double');
fclose(fid);
If I open the file asdf.txt with notepad, I can see when comes the first new line (at the position 190). I checked what value is occupying that position (taking into account the 8 bits of the double), and there is the 10 (ASCII equivalent to new line), in the sixth position of the 24th double-precision value. Exactly the first value which becomes corrupted when reading the data.

Connectez-vous pour commenter.

Réponse acceptée

James Tursa
James Tursa le 20 Avr 2016
Modifié(e) : James Tursa le 20 Avr 2016
Don't open the file as a text file with 'wt'. Instead, open it as binary by leaving off the 't' part. E.g.,
fid = fopen('asdf.txt','w');
(And, since it is a binary file you would probably use a different file extension other than .txt)
  1 commentaire
Dani Tormo
Dani Tormo le 21 Avr 2016
Like a charm.
Thanks!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Workspace Variables and MAT-Files dans Help Center et File Exchange

Produits

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by