rodins
rodins

Reputation: 316

What's the Java's float.floatToRawIntBits equivalent method in C#?

What's the Java's float.floatToRawIntBits method implementation in C# ?

Upvotes: 3

Views: 1144

Answers (1)

Bas
Bas

Reputation: 27105

If I understand the Java version correctly it should be:

        float value = 123.23F;

        byte[] bytes = BitConverter.GetBytes(value);

        int result = BitConverter.ToInt32(bytes, 0);

This puts the bytes representing the float into an integer.

Alternatively, a more complex (but probably faster) way to do it is to create a struct:

    [StructLayout(LayoutKind.Explicit)]
    public struct FloatToIntConverter
    {
        [FieldOffset(0)]
        public int IntValue;
        [FieldOffset(0)]
        public float FloatValue;
    }

        FloatToIntConverter converter = new FloatToIntConverter();
        converter.FloatValue = value;
        int result2 = converter.IntValue;

Upvotes: 9

Related Questions