How to write a long to an SD card?
Microcontrolled
Posts: 2,461
Hi,
I'm writing a program that needs to write some raw data to a file on an SD card. I'm using fsrw (and I'm too far into the project to switch to SD_FAT3.0) which doesn't support writing longs. Speed is essential, so I can't convert to decimal string and unconvert when I read the card. How would I write a long to an SD card using the pputc method? Has anyone else worked with this?
Thanks,
Microcontrolled
I'm writing a program that needs to write some raw data to a file on an SD card. I'm using fsrw (and I'm too far into the project to switch to SD_FAT3.0) which doesn't support writing longs. Speed is essential, so I can't convert to decimal string and unconvert when I read the card. How would I write a long to an SD card using the pputc method? Has anyone else worked with this?
Thanks,
Microcontrolled
Comments
XXX.pputc( FOO.byte0 )
XXX.pputc( FOO.byte1 )
XXX.pputc( FOO.byte2 )
XXX.pputc( FOO.byte3 )
If you want the bytes in some other order, just write them in the order you want.
You could also use pwrite to write them in the same order:
XXX.pwrite( @FOO, 4 )
pputc(longvalue.byte[1]
etc.
Depending on big/little ending of what read the SD card, you may need to start with byte[3] and work down to 0
John Abshier
As long as you write to the card and read from the card the same way, you shouldn't have to worry about big/little endianess.
So you could do it:
pputc(byte[@myLong])
pputc(byte[@myLong + 1])
pputc(byte[@myLong + 2])
pputc(byte[@myLong + 3])
This is pretty much the same as Mike's code (and I think John's). But if you have and array of longs you could use and index instead of "+1" etc and just continue across long boundries. You'd want to make sure you write (and read) in multiples of four.
As I said earlier, as long as you use the same order to write the long back to memory, the endianess should take care of itself.
For instance, if you can buffer up 10 longs into an array, and then write the entire
10-element array at once with a single pwrite call, you'll gain speed.
100 longs would be significantly faster than 10, and 1000 even more so.
You can write an array of say 30 longs with
pwrite(@longarr, 30*4)
All of this is to reduce or eliminate the spin overhead of the pputc calls.
I suspect the pwrite(@longvar, 4) would almost certainly be faster than four
pputc calls as well (but I haven't timed it).