Skip to content

[API Proposal]: BitOperations.ReverseBits #125879

Description

@saucecontrol

-- Commented edited by area owners to match: #125879 (comment)

Note

This comment was generated with AI (GitHub Copilot).

Revised API Proposal: IBinaryInteger<TSelf>.ReverseBits

Background and Motivation

Bit reversal is a common operation in CRC computation, Huffman coding (DEFLATE), ASN.1 named bit lists, FFT (decimation-in-time), and cryptographic key usage parsing. The runtime already contains 5+ private/internal implementations of this operation:

  • Crc32ParameterSet.ReverseBits(uint) — CRC-32 computation
  • Crc64ParameterSet.ReverseBits(ulong) — CRC-64 computation
  • AsnDecoder.ReverseBitsPerByte(Span<byte>) — ASN.1 named bit list decoding
  • X509KeyUsageExtension.ReverseBitOrder(byte) — X.509 certificate key usage
  • HuffmanTree.BitReverse(uint, int) — DEFLATE decompression

Hardware acceleration exists on ARM64 (rbit via ArmBase.ReverseElementBits) and recent x86 (AVX-512 BMM via Avx512Bmm.ReverseBits), but there is no general-purpose public API.

Prior art: Rust has reverse_bits() on all integer primitives. LLVM has llvm.bitreverse. Python has no built-in but int.bit_length() is commonly paired with manual reversal. C++ has std::bitset but no scalar intrinsic.

API Surface

Per @tannergooding's feedback, this is placed on IBinaryInteger<TSelf> as a static virtual method with a default interface method (DIM), rather than on BitOperations.

namespace System.Numerics;

public interface IBinaryInteger<TSelf> : IBinaryNumber<TSelf>, IShiftOperators<TSelf, int, TSelf>
    where TSelf : IBinaryInteger<TSelf>?
{
    // EXISTING:
    // static virtual TSelf LeadingZeroCount(TSelf value);
    // static abstract TSelf PopCount(TSelf value);
    // static virtual TSelf RotateLeft(TSelf value, int rotateAmount);
    // static virtual TSelf RotateRight(TSelf value, int rotateAmount);
    // static abstract TSelf TrailingZeroCount(TSelf value);

+   static virtual TSelf ReverseBits(TSelf value);
}

Optimized implementations on all built-in integer types:

namespace System;

public readonly partial struct Byte : IBinaryInteger<byte>
{
+   public static byte ReverseBits(byte value);
}

public readonly partial struct SByte : IBinaryInteger<sbyte>
{
+   public static sbyte ReverseBits(sbyte value);
}

public readonly partial struct UInt16 : IBinaryInteger<ushort>
{
+   public static ushort ReverseBits(ushort value);
}

public readonly partial struct Int16 : IBinaryInteger<short>
{
+   public static short ReverseBits(short value);
}

public readonly partial struct UInt32 : IBinaryInteger<uint>
{
+   public static uint ReverseBits(uint value);
}

public readonly partial struct Int32 : IBinaryInteger<int>
{
+   public static int ReverseBits(int value);
}

public readonly partial struct UInt64 : IBinaryInteger<ulong>
{
+   public static ulong ReverseBits(ulong value);
}

public readonly partial struct Int64 : IBinaryInteger<long>
{
+   public static long ReverseBits(long value);
}

public readonly partial struct UIntPtr : IBinaryInteger<nuint>
{
+   public static nuint ReverseBits(nuint value);
}

public readonly partial struct IntPtr : IBinaryInteger<nint>
{
+   public static nint ReverseBits(nint value);
}

public readonly partial struct UInt128 : IBinaryInteger<UInt128>
{
+   public static UInt128 ReverseBits(UInt128 value);
}

public readonly partial struct Int128 : IBinaryInteger<Int128>
{
+   public static Int128 ReverseBits(Int128 value);
}

public readonly partial struct Char : IBinaryInteger<char>
{
+   static char IBinaryInteger<char>.ReverseBits(char value);
}

API Usage

// Direct usage on primitive types
uint reversed = uint.ReverseBits(0x0000_0001u); // 0x8000_0000u
byte b = byte.ReverseBits(0xAA); // 0x55

// Generic math usage
T ReverseBitsGeneric<T>(T value) where T : IBinaryInteger<T>
    => T.ReverseBits(value);

Design Decisions

static virtual with DIM (not static abstract): The DIM writes the value's bytes, reverses bits within each byte, reverses byte order, and reads back. This is slower than the optimized implementations but works for any IBinaryInteger<TSelf> implementer without requiring them to override it.

On IBinaryInteger<TSelf> (not BitOperations): This follows the generic math pattern established by PopCount, RotateLeft, RotateRight, LeadingZeroCount, and TrailingZeroCount. It enables generic programming over any integer type.

Hardware intrinsics: The uint and ulong implementations use ArmBase.ReverseElementBits (ARM rbit instruction) when available, with a software fallback using the standard bit-swap algorithm. All smaller/larger types delegate through these, so they benefit transitively. Methods are also marked [Intrinsic] for future JIT intrinsification.

BigInteger uses the DIM: The DIM reverses bits within the minimal two's complement byte representation. An optimized override could be added in a follow-up.

Alternatives Considered

  • BitOperations static methods only: The original proposal. Rejected per tannergooding's feedback — the generic math interface is the right home for this.
  • static abstract (no DIM): Would force all IBinaryInteger implementers to provide their own implementation. The DIM is acceptable despite being slower.

Risks

  • No binary breaking changes: This is purely additive.
  • Source breaking changes: Extremely unlikely — ReverseBits is not a commonly-defined method name that would conflict with extension methods.
  • Performance: The DIM is intentionally slower for unknown types. All built-in types have O(1) hardware-friendly implementations using ARM intrinsics where available.

Prototype

Working prototype with tests: api-proposal/reverse-bits

Activity

  1. added
    api-suggestion
    on Mar 21, 2026
  2. added
    untriaged
    on Mar 21, 2026
  3. dotnet-policy-service commented on Mar 21, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-numerics
    See info in area-owners.md if you want to be subscribed.

  4. vcsjones commented on Mar 21, 2026

    @vcsjones
    Member

    smaller type overloads

    There a few places in S.S.Cryptography where doing it on a byte would be helpful. For example:

    private static byte ReverseBitOrder(byte b) => (byte)(unchecked(b * 0x0202020202ul & 0x010884422010ul) % 1023);

    I don't know one way or another if it can or should be an intrinsic but it would seem neater to round out the API.

  5. added
    api-ready-for-review
    and removed
    api-suggestion
    untriaged
    on Mar 21, 2026
  6. stephentoub commented on Mar 21, 2026

    @stephentoub
    Member

    @tannergooding:

    • Is BitOperations the right place for such operations? I've lost track of whether we'd want it there or promoted to the generic math interfaces or somewhere else.
    • If not in the math interfaces, any reason we wouldn't want a UInt128 overload as well?
  7. tannergooding commented on Mar 23, 2026

    @tannergooding
    Member

    I think we would want this on the math interfaces (IBinaryInteger in particular), just with noting the DIM would be slower here (which is acceptable) as it functionally has to write the bytes, reverse the bits of the bytes, and then read those bits back. I'm not aware of an optimized trick that will work otherwise for any integer.

  8. kevincathcart-cas commented on Mar 23, 2026

    @kevincathcart-cas

    Putting it on IBinaryInteger does come with the consideration that with that variable sized binary integers (like BigInteger) the output could give some unexpected results. Notably reversing bits twice might could up with a different value than you started with. This wouldn't be the only method in that interface which gives results that could be unexpected when using such types, although this one does seem to be a bit more striking than some of the other oddities.

    Unlikely to be a showstopper, but thought it was worth pointing out.

  9. stephentoub commented on Mar 23, 2026

    @stephentoub
    Member

    Note

    This comment was generated with AI (GitHub Copilot).

    Revised API Proposal: IBinaryInteger<TSelf>.ReverseBits

    Background and Motivation

    Bit reversal is a common operation in CRC computation, Huffman coding (DEFLATE), ASN.1 named bit lists, FFT (decimation-in-time), and cryptographic key usage parsing. The runtime already contains 5+ private/internal implementations of this operation:

    • Crc32ParameterSet.ReverseBits(uint) — CRC-32 computation
    • Crc64ParameterSet.ReverseBits(ulong) — CRC-64 computation
    • AsnDecoder.ReverseBitsPerByte(Span<byte>) — ASN.1 named bit list decoding
    • X509KeyUsageExtension.ReverseBitOrder(byte) — X.509 certificate key usage
    • HuffmanTree.BitReverse(uint, int) — DEFLATE decompression

    Hardware acceleration exists on ARM64 (rbit via ArmBase.ReverseElementBits) and recent x86 (AVX-512 BMM via Avx512Bmm.ReverseBits), but there is no general-purpose public API.

    Prior art: Rust has reverse_bits() on all integer primitives. LLVM has llvm.bitreverse. Python has no built-in but int.bit_length() is commonly paired with manual reversal. C++ has std::bitset but no scalar intrinsic.

    API Surface

    Per @tannergooding's feedback, this is placed on IBinaryInteger<TSelf> as a static virtual method with a default interface method (DIM), rather than on BitOperations.

    namespace System.Numerics;
    
    public interface IBinaryInteger<TSelf> : IBinaryNumber<TSelf>, IShiftOperators<TSelf, int, TSelf>
        where TSelf : IBinaryInteger<TSelf>?
    {
        // EXISTING:
        // static virtual TSelf LeadingZeroCount(TSelf value);
        // static abstract TSelf PopCount(TSelf value);
        // static virtual TSelf RotateLeft(TSelf value, int rotateAmount);
        // static virtual TSelf RotateRight(TSelf value, int rotateAmount);
        // static abstract TSelf TrailingZeroCount(TSelf value);
    
    +   static virtual TSelf ReverseBits(TSelf value);
    }

    Optimized implementations on all built-in integer types:

    namespace System;
    
    public readonly partial struct Byte : IBinaryInteger<byte>
    {
    +   public static byte ReverseBits(byte value);
    }
    
    public readonly partial struct SByte : IBinaryInteger<sbyte>
    {
    +   public static sbyte ReverseBits(sbyte value);
    }
    
    public readonly partial struct UInt16 : IBinaryInteger<ushort>
    {
    +   public static ushort ReverseBits(ushort value);
    }
    
    public readonly partial struct Int16 : IBinaryInteger<short>
    {
    +   public static short ReverseBits(short value);
    }
    
    public readonly partial struct UInt32 : IBinaryInteger<uint>
    {
    +   public static uint ReverseBits(uint value);
    }
    
    public readonly partial struct Int32 : IBinaryInteger<int>
    {
    +   public static int ReverseBits(int value);
    }
    
    public readonly partial struct UInt64 : IBinaryInteger<ulong>
    {
    +   public static ulong ReverseBits(ulong value);
    }
    
    public readonly partial struct Int64 : IBinaryInteger<long>
    {
    +   public static long ReverseBits(long value);
    }
    
    public readonly partial struct UIntPtr : IBinaryInteger<nuint>
    {
    +   public static nuint ReverseBits(nuint value);
    }
    
    public readonly partial struct IntPtr : IBinaryInteger<nint>
    {
    +   public static nint ReverseBits(nint value);
    }
    
    public readonly partial struct UInt128 : IBinaryInteger<UInt128>
    {
    +   public static UInt128 ReverseBits(UInt128 value);
    }
    
    public readonly partial struct Int128 : IBinaryInteger<Int128>
    {
    +   public static Int128 ReverseBits(Int128 value);
    }
    
    public readonly partial struct Char : IBinaryInteger<char>
    {
    +   static char IBinaryInteger<char>.ReverseBits(char value);
    }

    API Usage

    // Direct usage on primitive types
    uint reversed = uint.ReverseBits(0x0000_0001u); // 0x8000_0000u
    byte b = byte.ReverseBits(0xAA); // 0x55
    
    // Generic math usage
    T ReverseBitsGeneric<T>(T value) where T : IBinaryInteger<T>
        => T.ReverseBits(value);

    Design Decisions

    static virtual with DIM (not static abstract): The DIM writes the value's bytes, reverses bits within each byte, reverses byte order, and reads back. This is slower than the optimized implementations but works for any IBinaryInteger<TSelf> implementer without requiring them to override it.

    On IBinaryInteger<TSelf> (not BitOperations): This follows the generic math pattern established by PopCount, RotateLeft, RotateRight, LeadingZeroCount, and TrailingZeroCount. It enables generic programming over any integer type.

    Hardware intrinsics: The uint and ulong implementations use ArmBase.ReverseElementBits (ARM rbit instruction) when available, with a software fallback using the standard bit-swap algorithm. All smaller/larger types delegate through these, so they benefit transitively. Methods are also marked [Intrinsic] for future JIT intrinsification.

    BigInteger uses the DIM: The DIM reverses bits within the minimal two's complement byte representation. An optimized override could be added in a follow-up.

    Alternatives Considered

    • BitOperations static methods only: The original proposal. Rejected per tannergooding's feedback — the generic math interface is the right home for this.
    • static abstract (no DIM): Would force all IBinaryInteger implementers to provide their own implementation. The DIM is acceptable despite being slower.

    Risks

    • No binary breaking changes: This is purely additive.
    • Source breaking changes: Extremely unlikely — ReverseBits is not a commonly-defined method name that would conflict with extension methods.
    • Performance: The DIM is intentionally slower for unknown types. All built-in types have O(1) hardware-friendly implementations using ARM intrinsics where available.

    Prototype

    Working prototype with tests: api-proposal/reverse-bits

  10. KevinCathcart commented on Apr 28, 2026

    @KevinCathcart
    Contributor

    As discussed over in Random.Next, there is no API on IBinaryInteger that exposes the native bit format, only an API that exposes two's complement representation. This means that the best the DIM can do is reverse the bits of the twos complement representation. If I make a type that implements this interface, but is explicitly documented as representing the numbers in some other binary integer format (sign-magnitude, ones-compliment, whatever), then callers might reasonably expect that this would reverse the bits in that format (especially if all bit patterns are valid), and the DIM would not do that.

    We might be able to tolerate this (libraries defining with such types should be able to multi-target and release an update defining the function in 11 or newer targets), but I thought it was worth stating here explicitly, so the implications are properly considered. The fact that the DIM is only easily accessible in a generic context, and would require being exposed as a static for such types to be conveniently usable does imply reduced room for confusion.

  11. tannergooding commented on Apr 28, 2026

    @tannergooding
    Member

    As was covered on the other issue(s), while the underlying storage format does not have to strictly be "two's complement" (see BigInteger), the number is already expected to behave as if two's complement. This is a fundamental part of the interface and for APIs like the Popcnt, LeadingZeroCount, TrailingZeroCount, Rotate, Shift, and even the Read/Write*Endian APIs to behave correctly.

    You can run into a few quirks, like with BigInteger compressing down to the shortest two's complement representation and so [0b1111_1111, 0b1111_1110] >> 1 (bytes as big endian) for signed can become [0b1111_1111] instead of [0b1111_1111, 0b1111_1111] (simplified example assuming byte instead of uint/nuint storage), but it still fundamentally behaves as if the underlying represented value was the correct two's complement number.

  12. hamarb123 commented on May 6, 2026

    @hamarb123
    Contributor

    Wrote this today, so am giving a thumbs up lol

    Image
  13. added this to the 11.0.0 milestone on May 6, 2026
  14. bartonjs commented on May 6, 2026

    @bartonjs
    Member

    @tannergooding Remember that we usually review the proposal in the top post; so if the generic math version is what you intend to propose, someone should edit it into the top (and change the title)

  15. tannergooding commented on May 6, 2026

    @tannergooding
    Member

    Thanks, thought this one had already been updated.

  16. bartonjs commented on May 12, 2026

    @bartonjs
    Member

    Video

    Looks good as proposed.

    namespace System.Numerics
    {
        public partial interface IBinaryInteger<TSelf> : IBinaryNumber<TSelf>, IShiftOperators<TSelf, int, TSelf>
            where TSelf : IBinaryInteger<TSelf>?
        {
            static virtual TSelf ReverseBits(TSelf value);
        }
    }
    
    // Public/implicit on all types except char (explicitly special handled), and BigInteger (either explicit or via DIM)
    
    namespace System
    {
        public readonly partial struct Byte : IBinaryInteger<byte>
        {
           public static byte ReverseBits(byte value);
        }
    
        public readonly partial struct SByte : IBinaryInteger<sbyte>
        {
           public static sbyte ReverseBits(sbyte value);
        }
    
        public readonly partial struct UInt16 : IBinaryInteger<ushort>
        {
           public static ushort ReverseBits(ushort value);
        }
    
        public readonly partial struct Int16 : IBinaryInteger<short>
        {
           public static short ReverseBits(short value);
        }
    
        public readonly partial struct UInt32 : IBinaryInteger<uint>
        {
           public static uint ReverseBits(uint value);
        }
    
        public readonly partial struct Int32 : IBinaryInteger<int>
        {
           public static int ReverseBits(int value);
        }
    
        public readonly partial struct UInt64 : IBinaryInteger<ulong>
        {
           public static ulong ReverseBits(ulong value);
        }
    
        public readonly partial struct Int64 : IBinaryInteger<long>
        {
           public static long ReverseBits(long value);
        }
    
        public readonly partial struct UIntPtr : IBinaryInteger<nuint>
        {
           public static nuint ReverseBits(nuint value);
        }
    
        public readonly partial struct IntPtr : IBinaryInteger<nint>
        {
           public static nint ReverseBits(nint value);
        }
    
        public readonly partial struct UInt128 : IBinaryInteger<UInt128>
        {
           public static UInt128 ReverseBits(UInt128 value);
        }
    
        public readonly partial struct Int128 : IBinaryInteger<Int128>
        {
           public static Int128 ReverseBits(Int128 value);
        }
    
        public readonly partial struct Char : IBinaryInteger<char>
        {
           static char IBinaryInteger<char>.ReverseBits(char value);
        }
    }
  17. added
    api-approved
    and removed
    api-ready-for-review
    on May 12, 2026
  18. modified the milestones: 11.0.0, 12.0.0 on Aug 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedarea-System.Numerics

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions