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

DataOutputStream out = new DataOutputStream(new FileOutputStream("foo.dat"));
out.writeInt(1234);
out.writeShort(30000);
out.writeFloat(256.384f);

我正在使用以下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);

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

有帮助吗?

解决方案

只需使用<Foundation/Foundation.h>提供的功能和类型。

NSSwappedFloat bigEndianFloat;
memcpy(&bigEndianFloat, [[file readDataOfLength:4] bytes], 4);
float floatValue = NSSwapBigFloatToHost(bigEndianFloat);

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

其他提示

很抱歉,我无法提供完整的答案,但我可以说Java float按照本文档保存到文件中,作为浮点数的四字节IEEE 754表示:

http: //java.sun.com/j2se/1.5.0/docs/api/java/lang/Float.html#floatToIntBits(float)

它描述了保存的值的确切结构,因此您可以将其作为int读取并手动将有效数和指数的位解析为浮点数。看起来应该有一个库调用来解析打包到这种格式的int中的浮点值。希望其他人知道一个库调用来处理这个问题。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top