Given the following Java code for generating a binary file:
DataOutputStream out = new DataOutputStream(new FileOutputStream('foo.dat')); out.writeInt(1234); out.writeShort(30000); out.writeFloat(256.384f);
I’m using the following Objective-C code and manage to parse the int and the short values:
NSString *path = [[NSBundle mainBundle] pathForResource:@'foo' ofType:@'dat']; NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:path]; unsigned long intValue; memcpy(&intValue, [[file readDataOfLength:4] bytes], 4); intValue = NSSwapBigLongToHost(intValue); unsigned short shortValue; memcpy(&shortValue, [[file readDataOfLength:2] bytes], 2); shortValue = NSSwapBigShortToHost(shortValue);
My problem for now is with the float value: any clues on how to parse it?
Just us the functions and types provided by
<Foundation/Foundation.h>.Note that they use a special type to hold the float before the bytes are swapped. This is because if you swap the bytes of a floating point value, it can be changed into a Signaling NaN, and on some processors, this will cause a hardware exception by just assigning it to a variable.