user2637015
user2637015

Reputation: 723

Writing float to file in little endian?

public static void writeShortLE(DataOutputStream out, short value) {
  out.writeByte(value & 0xFF);
  out.writeByte((value >> 8) & 0xFF);
}

public static void writeIntLE(DataOutputStream out, int value) {
  out.writeByte(value & 0xFF);
  out.writeByte((value >> 8) & 0xFF);
  out.writeByte((value >> 16) & 0xFF);
  out.writeByte((value >> 24) & 0xFF);
}

I'm using the two methods above for writing a short and an int.

My question is: how to write a float?

Upvotes: 2

Views: 1368

Answers (2)

Oz Shabat
Oz Shabat

Reputation: 1622

For Kotlin's users, just a complementary answer to arshajii's one:

fun writeFloat32LE(out: DataOutputStream, valToAdd: Float) {
    writeIntLE(out, valToAdd.toRawBits())
}


fun writeIntLE(out: DataOutputStream, value: Int) {
    out.writeByte(value and 0xFF)
    out.writeByte(value shr 8 and 0xFF)
    out.writeByte(value shr 16 and 0xFF)
    out.writeByte(value shr 24 and 0xFF)
}

And the read function can be simplified to:

fun readFloat32LE(): Float {
    val nInt = readIntLE()
    return Float.fromBits(nInt)
}

Upvotes: 0

arshajii
arshajii

Reputation: 129497

You can use Float.floatToRawIntBits to obtain an int consisting of the bits of the given float argument, and then write that via writeIntLE:

public static void writeFloatLE(DataOutputStream out, float value) {
    writeIntLE(Float.floatToRawIntBits(value));
}

To read back the float, you can read an int and use Float.intBitsToFloat to obtain the float value from it.


From the linked documentation for Float.floatToRawIntBits:

Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "single format" bit layout, preserving Not-a-Number (NaN) values.

Bit 31 (the bit that is selected by the mask 0x80000000) represents the sign of the floating-point number. Bits 30-23 (the bits that are selected by the mask 0x7f800000) represent the exponent. Bits 22-0 (the bits that are selected by the mask 0x007fffff) represent the significand (sometimes called the mantissa) of the floating-point number.

Upvotes: 3

Related Questions