字节切换Java浮动以用于C++;程序 我必须将一系列java浮点转换成Little Endian,以便C++程序正确读取。我正在处理大量的浮动

字节切换Java浮动以用于C++;程序 我必须将一系列java浮点转换成Little Endian,以便C++程序正确读取。我正在处理大量的浮动,java,floating-point,endianness,Java,Floating Point,Endianness,我尝试过ByteBuffer、GeoSoft和ApacheCommons I/O实用程序。大约每1%的时间,一些浮点数在转换为整数位时似乎被识别为NaN值。我甚至尝试了FLOAT.floatToRawIntBits来解决这个问题,但是没有用 作为我所说的一个例子,当问题出现时,我会给出一个具体的例子 下面是一系列正确交换的浮动 8.93516466e-02 -1.0571138 -2.2298267 0.042286094 0.8592236 0.5098497 0.67256117 然而,我

我尝试过ByteBuffer、GeoSoft和ApacheCommons I/O实用程序。大约每1%的时间,一些浮点数在转换为整数位时似乎被识别为NaN值。我甚至尝试了FLOAT.floatToRawIntBits来解决这个问题,但是没有用

作为我所说的一个例子,当问题出现时,我会给出一个具体的例子

下面是一系列正确交换的浮动

8.93516466e-02
-1.0571138
-2.2298267
0.042286094
0.8592236
0.5098497
0.67256117
然而,我看到:

6.9055E-41
-1.0571138
-2.2298267
0.042286094
0.8592236
0.5098497
0.67256117
你能告诉我如何“吸收”这些被识别为NaN的位序列吗

我正在粘贴用于促进字节交换的代码

 public static float swap (float value)
  {
    int intValue = Float.floatToRawIntBits (value);
    intValue = swap (intValue);
    return Float.intBitsToFloat (intValue);
  }

 public static int swap (int value)
  {
    int b1 = (value >>  0) & 0xff;
    int b2 = (value >>  8) & 0xff;
    int b3 = (value >> 16) & 0xff;
    int b4 = (value >> 24) & 0xff;
    return b1 << 24 | b2 << 16 | b3 << 8 | b4 << 0;
  }
这是我打印出来的代码--告诉我是否有错:

public static float testSwap (float value)
{
    int intValue = Float.floatToRawIntBits (value);
    System.out.println(Integer.toBinaryString(intValue));
    intValue = swap (intValue);
    System.out.println(Integer.toBinaryString(intValue));
        return Float.intBitsToFloat (intValue);
}

不能通过交换字节将一个浮点转换为另一个浮点。您必须具有原始的
int
值,否则某些值将如您所见被损坏。这是因为float将标准化其值,并且并非所有位模式在Java中都有效


我建议使用ByteBuffer以本机字节顺序读取FloatBuffer。这样,您就不会损坏您的值。

您能告诉我们您发布的示例值的确切位模式吗?如果你能在第一个方面做这一点,对于java端(交换之前)和C++端来说,这将是特别有用的。作为澄清,你想要1和0,对吗?我不能访问C++程序本身。但是,我将向您展示我在交换程序中输入的内容,以及从交换程序中输出的内容。如果你还需要别的东西,请纠正我——我对计算机编程语言不太精通。@TedHopp我打印了位模式。请告诉我这是否是你想要的。十六进制或二进制,最重要的位或十六进制数字在左边。我想我得到了你需要的。我有一个问题:使用FloatBuffer和一般的ByteBuffer有什么区别?当我尝试使用ByteBuffer时,我也遇到了同样的问题。具体来说,FloatBuffer如何解决这个问题?我问这个不是因为我怀疑你的方法。相反,我只是想了解更多。我也在读源代码。我会试试你的建议。@newproduct如果你对ByteBuffer或FloatBuffer有问题,那是因为你没有用
.order(ByteOrder.LITTE\u ENDIAN)
设置字节顺序,而你自己却试图做得不正确。
public static float testSwap (float value)
{
    int intValue = Float.floatToRawIntBits (value);
    System.out.println(Integer.toBinaryString(intValue));
    intValue = swap (intValue);
    System.out.println(Integer.toBinaryString(intValue));
        return Float.intBitsToFloat (intValue);
}