How do you write binary data to a file? I want to write floats to a file, raw, and then read them back as floats. How do you do that?
A:
Been experimenting with this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file = [documentsDirectory stringByAppendingPathComponent:@"binaryData"];
float b = 32.0f;
NSMutableData *data = [NSMutableData dataWithLength:sizeof(float)];
[data appendBytes:&b length:sizeof(float)];
[data writeToFile:file atomically:YES];
NSData *read = [NSData dataWithContentsOfFile:file];
float b2;
NSRange test = {0,4};
[read getBytes:&b2 range:test];
The weird thing is that the file written seems to be 8 bytes and not 4. It is even possible to init the nsdata with 0 length, append a float and then write, and then the file will be 4 bytes. Why is NSData adding 4 bytes by default? A NSData with length 4 should result in a file with length 4, not 8.
quano
2009-10-06 16:37:33
Can you use a hex editor to examine the contents of the file when it has 8 bytes? Seems to me you should be able to pick out which 4 are your float and the other 4 may give you a clue as to what's going wrong.
Tim
2009-10-06 16:46:24
Indeed. The last 4 is the float. The file looks like this: 00 00 00 00 00 00 00 42
quano
2009-10-06 16:53:53
Apparently initing a NSMutableData with a length causes it to append that length to its data and point to the space afterwards. Initing it with length 0 is the solution. Then one can ask oneself why one would want to init it with any other length than 0 at all.
quano
2009-10-06 19:49:11