Skip to content

[API Proposal]: Bit manipulation method for BFloat16 #119874

@huoyaoyuan

Description

@huoyaoyuan

Background and motivation

#98643 (comment)

Add bit manipulation operations for the newly introduced BFloat16 type (#96295), to align with other floating point types. The method list is taken from CoreLib methods using Half.

API Proposal

namespace System;

public class BitConverter
{
+    public short BFloat16BitsToInt16(BFloat16 value);
+    public ushort BFloat16BitsToUInt16(BFloat16 value);
+    public static BFloat16 Int16BitsToBFloat16(short value);
+    public static BFloat16 UInt16BitsToBFloat16(ushort value);
}

namespace System.Buffers.Binary;

public class BinaryPrimitives
{
+    public static void WriteBFloat16BigEndian(Span<byte> destination, BFloat16 value);
+    public static void WriteBFloat16LittleEndian(Span<byte> destination, BFloat16 value);
+    public static bool TryWriteBFloat16BigEndian(Span<byte> destination, BFloat16 value);
+    public static bool TryWriteBFloat16LittleEndian(Span<byte> destination, BFloat16 value);
+    public static void ReadBFloat16BigEndian(ReadOnlySpan<byte> source, out BFloat16 value);
+    public static void ReadBFloat16LittleEndian(ReadOnlySpan<byte> source, out BFloat16 value);
+    public static bool TryReadBFloat16BigEndian(ReadOnlySpan<byte> source, out BFloat16 value);
+    public static bool TryReadBFloat16LittleEndian(ReadOnlySpan<byte> source, out BFloat16 value);
}

namespace System.IO;

public class BinaryReader
{
+    public virtual BFloat16 ReadBFloat16();
}

public class BinaryWriter
{
+    public virtual void WriteBFloat16(BFloat16 value);
}

API Usage

short bitValue = BitConverter.BFloat16BitsToInt16(f);
bool isPositive = (bitValue & 0x80) != 0;

Alternative Designs

Do not expose the BinaryPrimitives/BinaryReader/BinaryWriter methods, depend on generic math interfaces instead.

Alternatively, we can choose to not expose the BitConverter methods at all, as there is already Unsafe.BitCast.

Risks

Unlike IEEE754 floating point types, there are more variations of floating point types in use in different areas that we may add in the future. Adding more direct support to the core types can cause bloat in API surface. Instead, we should rely on generic math interface as much as possible, to avoid duplicating API surface or taking dependency on too many types from the core types.

Add the methods will also lose the opportunity to move BFloat16 out of CoreLib.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions