如何使用Cocoa Touch解析带浮点数(生成Java)的二进制文件?

Ari*_*lka 2 java parsing cocoa-touch

给出以下用于生成二进制文件的Java代码:

DataOutputStream out = new DataOutputStream(new FileOutputStream("foo.dat"));
out.writeInt(1234);
out.writeShort(30000);
out.writeFloat(256.384f);
Run Code Online (Sandbox Code Playgroud)

我正在使用以下Objective-C代码并设法解析int和short值:

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);
Run Code Online (Sandbox Code Playgroud)

我现在的问题是浮点值:关于如何解析它的任何线索?

Der*_*ter 5

只是我们提供的功能和类型<Foundation/Foundation.h>.

NSSwappedFloat bigEndianFloat;
memcpy(&bigEndianFloat, [[file readDataOfLength:4] bytes], 4);
float floatValue = NSSwapBigFloatToHost(bigEndianFloat);
Run Code Online (Sandbox Code Playgroud)

请注意,在交换字节之前,它们使用特殊类型来保存浮点数.这是因为如果您交换浮点值的字节,它可以更改为信令NaN,并且在某些处理器上,这将通过将其分配给变量而导致硬件异常.