C# .NET 4.6 equivalent of Unsafe.As

Viewed 231

What is a C# .NET 4.6 equivalent of this:

    public static float UnpackFloat32(this ulong value)
    {
        return Unsafe.As<ulong, float>(ref value);
    }

The Unsafe.As isn't available in 4.6.

1 Answers

You might even implement it in earlier .NET versions without unsafe code by using a structure with explicit layout:

[StructLayout(LayoutKind.Explicit)]
struct FloatUlongConverter
{
    [FieldOffset(0)] public float floatValue;
    [FieldOffset(0)] public ulong ulongValue;
}

public static ulong PackFloat32(this float value)
{
    var converter = new FloatUlongConverter();
    converter.floatValue = value;
    return converter.ulongValue;
}

public static float UnpackFloat32(this ulong value)
{
    var converter = new FloatUlongConverter();
    converter.ulongValue = value;
    return converter.floatValue;
}
Related