Hobbyist
Hobbyist

Reputation: 16192

C# equivalent to Java's Float.floatToIntBits

I've been writing a port of a networking library from Java and this is the last line of code I have yet to decipher and move on over. The line of code is as follows:

Float.floatToIntBits(Float);

Which returns an integer.

The code of floatToIntBits in Java

public static int floatToIntBits(float value) {
        int result = floatToRawIntBits(value);
        // Check for NaN based on values of bit fields, maximum
        // exponent and nonzero significand.
        if ( ((result & FloatConsts.EXP_BIT_MASK) ==
              FloatConsts.EXP_BIT_MASK) &&
             (result & FloatConsts.SIGNIF_BIT_MASK) != 0)
            result = 0x7fc00000;
        return result;
    }

I'm not nearly experienced enough with memory and hex values to port this over myself, not to mention the bit shifting that's all over the place that's been driving me absolutely mad.

Upvotes: 2

Views: 1872

Answers (2)

Mike Strobel
Mike Strobel

Reputation: 25623

If you can compile with unsafe, this becomes trivial:

public static unsafe uint FloatToUInt32Bits(float f) {
    return *((uint*)&f);
}

Replace uint with int if you want to work with signed values, but I would say unsigned makes more sense. This is actually equivalent to Java's floatToRawIntBits(); floatToIntBits() is identical except that it always returns the same bitmask for all NaN values. If you want that functionality, you can just replicate that if statement from the Java version, but it's probably unnecesssary.

You'll need to switch on 'unsafe' support for your assembly, so it's up to you whether you want to go this route. It's not at all uncommon for high performance networking libraries to use unsafe code.

Upvotes: 1

Dmitry
Dmitry

Reputation: 14059

Take a look at the BitConverter class. For doubles it has methods DoubleToInt64Bits and Int64BitsToDouble. For floats you could do something like this:

float f = ...;
int i = BitConverter.ToInt32(BitConverter.GetBytes(f), 0);

Or changing endianness:

byte[] bytes = BitConverter.GetBytes(f);
Array.Reverse(bytes);
int i = BitConverter.ToInt32(bytes, 0);

Upvotes: 6

Related Questions