简体   繁体   中英

ByteSwapping Java Floats to use for C++ program

I have to convert a series of Java floats into Little Endian to be correctly read by a C++ program. I am working with a large amount of floats.

I have tried ByteBuffer, GeoSoft, and the Apache Commons I/O utilities. About every 1% of the time, some of the floats, when converted to IntBits, seem to be recognized as an NaN value. I've even tried FLOAT.floatToRawIntBits to solve the problem, but to no avail.

As an example of what I'm talking about, I am giving a specific instance when the problem arises.

Here are a series of floats which are correctly swapped..

8.93516466e-02
-1.0571138
-2.2298267
0.042286094
0.8592236
0.5098497
0.67256117

However, I am seeing this:

6.9055E-41
-1.0571138
-2.2298267
0.042286094
0.8592236
0.5098497
0.67256117

Can you please tell me how I can 'absorb' these sequences of Bits recognized as NaN?

I am pasting the code that I used to facilitate the byte swap.

 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;
  }

The problem number in this case is 8.93516466e-02

I printed out the bits before and after the swap and got this:

111101101101101111110111111111
11111111111111011011011000111101

This was my code to print this out -- tell me if it is wrong:

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);
}

You cannot convert a float into another float by swapping the bytes. You must have the original int value or some values will be corrupted as you have seen. This is because float will normalise its values and not all bit patterns are valid in Java.

I suggest reading using ByteBuffer for FloatBuffer in native byte order. This way you will not be corrupting you values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM