【发布时间】:2019-04-22 16:25:51
【问题描述】:
我正在尝试编写一个保存解析器,它将浮点数保存为小端,但是,Java 是大端的,所以我需要在写入时转换 FP 并再次返回,但这确实会导致一些浮点数不一致点数。
我尝试读入浮点数,转换为 int 位,反转 int 位,然后再转换回浮点数。
并将浮点数反向转换为原始 int 位,反转 int 位,然后重新转换回浮点数。
public void test()
{
//file contents (hex) 0x85, 0x76, 0x7e, 0xbd, 0x7f, 0xd8, 0xa8, 0x3e, 0x2f, 0xcb, 0x8f, 0x3d, 0x06, 0x7c, 0x70, 0x3f
RandomAccessFile iRAF = new RandomAccessFile(new File("input.test"), "r");
RandomAccessFile oRAF = new RandomAccessFile(new File("output.test"), "rw");
byte[] input = new byte[16];
iRAF.readFully(input);
float[] floats = new float[4];
for (int i = 0; i < 4; i++)
{
floats[i] = readFloat(iRAF);
}
writeFloats(oRAF, floats);
byte[] output = new byte[16];
oRAF.seek(0);
oRAF.readFully(output);
if (Arrays.equals(input, output) == false)
{
System.err.println(toHex(input));
System.err.println(toHex(output));
}
}
private String toHex(byte[] bytes)
{
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (int i = 0; i < bytes.length; i++)
{
sb.append(String.format("%02x", bytes[i])).append(" ");
}
return sb.toString();
}
public float readFloat(RandomAccessFile raf) throws IOException
{
return Float.intBitsToFloat(Integer.reverseBytes(Float.floatToRawIntBits(raf.readFloat())));
}
public void writeFloats(RandomAccessFile raf, float... floats) throws IOException
{
for (int i = 0; i < floats.length; i++)
raf.writeFloat(Float.intBitsToFloat(Integer.reverseBytes(Float.floatToRawIntBits(floats[i]))));
}
我希望输出具有与输入完全相同的十六进制值:
85 76 7e bd 7f d8 a8 3e 2f cb 8f 3d 06 7c 70 3f
但实际输出是:
85 76 7e bd 7f c0 00 00 2f cb 8f 3d 06 7c 70 3f
这是由于一些浮点舍入错误,或者可能是在将其转换为 NaN 值而不保留位时(尽管我认为这就是 Float.floatToRawIntBits() 的用途。
【问题讨论】:
-
Java 既不是大端也不是小端。这取决于硬件。你看过
ByteBuffer吗?它有一个方法来设置缓冲区的字节序(以及你放入其中的所有数据)。 -
这是一个使用
ByteBuffer的例子,如果有帮助请告诉我们:stackoverflow.com/questions/54542268/… -
@markspace 它确实有效,但是,在大多数情况下,它会使读取文件所需的时间增加一倍甚至三倍(取决于所述文件中的浮点数)(我正在重用相同的字节缓冲区,不是每次都创建一个新的)
-
你为什么用
Float.floatToRawIntBits(raf.readFloat())而不是raf.readInt()? -
@markspace Java 在任何平台上都是大端的。请参阅
RandomAccessFile和Data/Input/OutputStream的 Javadoc。
标签: java floating-point endianness