0

I'm working on a project with SDcard, and I would like to write int and long in a file.

If I try to write 0x1954 I had 0x5419 on my file with file.write() so I did a circular shifting like:

  data=(data<<8)|(data >> (16-8)); //circular shift    
  file.write((char*)&data,sizeof(data));

But with a long, I have 0x54195521 on my file instead of 0x19542155. So I don't know how to fix this. If you have any idea, I would like to read it ! (Or another way to do it)

Thanks !

  • Finally, after some searchs on internet, to have the maximum writing speed, I choose to keep the original writing and post-process it in Matlab. Thanks for your help ! – bouaaah Jul 31 '17 at 13:51
  • Please don't add "thank you" as an answer. Instead, accept the answer that you found most helpful. - From Review – Michel Keijzers Jul 31 '17 at 14:19
1

(Its not circular shifting, its bit shifting, the bits don't go round in a circle they disappear off the end and are lost forever.)

So in the library you are using you are writing bytes to the SD Card. If you write the data 0x1954 on the card you get 0x5419.
So what is happening is you are writing the least significant byte followed by the most significant. This is because you have take your int 0x1954 and cast it to a char[2] which contains c[0] = 0x54 and c[1] = 0x19 and then you write that out in the order c[0]c[1] et voila you have reversed you number.

The solution is to reverse the buffer before you write it:

char tmp = buf[0];
buf[0] = buf[1];
buf[1] = tmp;

HOWEVER - If you are only reading and writing from this code, who cares. As long as you read it in backwards does it matter how it is stored on the SD Card?

  • I'm not only reading and writing from this code, I will read my file with matlab later – bouaaah Jul 31 '17 at 12:07
  • @bouaaah - OK, didn't want you wasting time on it if it didn't matter. :) – Code Gorilla Jul 31 '17 at 12:10
  • Sry i not finished my comment and can't editing it so here is the full comment: (I don't lost my bits because I'm doing a right shift on MSB and left shift on LSB, so it's like a circular shifting) I'm not only reading and writing from this code, I will read my file with matlab later. And if i want to reverse the buffer like you did, it's only 3 lines for a int but for a long it will be 6 lines at least. And i need to be as fast as possible so i prefer to work with bits shifting/masking instead of writing/reading a temp variable. – bouaaah Jul 31 '17 at 12:15
  • but if it's the only solution i will do by this way ;) – bouaaah Jul 31 '17 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.