Skip to content

Implement IBinaryInteger<TSelf>.ReverseBits - #131145

Open
huoyaoyuan wants to merge 21 commits into
dotnet:mainfrom
huoyaoyuan:reverse-bits
Open

huoyaoyuan wants to merge 21 commits into
dotnet:mainfrom
huoyaoyuan:reverse-bits

Conversation

@huoyaoyuan

Copy link
Copy Markdown
Member

Closes #125879

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
13 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

}

/// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)" />
static BigInteger IBinaryInteger<BigInteger>.ReverseBits(BigInteger value)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Though it doesn't make much sense for BigInteger, I'm trying to design a rule that reasonably round-trips, and behaves consistently on 32/64bit and LE/BE platforms.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't look to be consistent for 32/64-bit right now? what about -(BigInt.One << 96)?

-- The ref assembly was also not updated

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The effective signed binary is .._FFFFFFFF_00000000_00000000_00000000, which is expected be treated samely with .._FFFFFFFF_00000000 case, which is included in the test. The expected result is round-tripping to itself. I can add a test caes for it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well test shows difference for -(BigInt.One << 64) case. I'll debug more.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've reworded the rules, refactored the condition checks and added more comments about tests. Hopefully it's more understandable now.

@huoyaoyuan huoyaoyuan added the community-contribution Indicates that the PR has been added by a community member label Jul 21, 2026
@huoyaoyuan

Copy link
Copy Markdown
Member Author

Manually tagging @dotnet/area-system-numerics as the bot misses.

@jeffhandley jeffhandley added this to the 12.0.0 milestone Aug 17, 2026
@jeffhandley

Copy link
Copy Markdown
Member

@tannergooding tagged you for review and I marked the PR and issue as .NET 12. If we get this merged before the RC2 snap date, I'd be comfortable seeking tactics approval for backport to .NET 11 if you are.


if (BitConverter.IsLittleEndian)
{
return TSelf.ReadBigEndian(bytes, isUnsigned: false);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can fail for a case like 1 on an unsigned type.

Comment on lines +296 to +301
if (Gfni.IsSupported)
{
Vector128<byte> vec = Vector128.CreateScalarUnsafe(value);
vec = Gfni.GaloisFieldAffineTransform(vec, Vector128.Create(0x8040201008040201).AsByte(), 0);
return vec.ToScalar();
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not convinced this is faster, especially not when factoring in the SIMD/GPR transition, the memory load, etc

It's likely being skewed by the microbenchmark.

@huoyaoyuan huoyaoyuan Aug 19, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The vector path shows 2.5x faster on uint32 even in dense loop unrolling benchmark, and undistinguishable time (<0.1ns) in scalar benchmark.
For dense case which consumes more memory and SIMD register, we could provide packed operation via TensorPrimitives.
For sparse use case, does it really matter for consumption for a few SIMD registers?

I know it can be skewed by microbenchmark given it's using SIMD effectively densely. However, xmm is used quite commonly. Would it matter?

@tannergooding tannergooding Aug 19, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's about how it interplays with the entire system. For vector, this is likely an optimization; but for simple scalar you are inserting multiple stalls (gpr to simd transitions), memory dependencies (likely uncached), and other considerations that likely make it a perf loss; particularly for code that isn't hot.

The scalar path will be around 9-16 cycles, depending on how well it pipelines. On the other hand, the vector path will also be 9-21 cycles (without factoring in the memory load cost), depending on how much penalty there is for the vmovd instructions (which have gotten slower on newer hardware, changing from <=3 to <=8 on regular cores and more on e-cores)

The GPR<->SIMD transition penalty can be a lot especially for hot code. Inversely the memory dependency can be a lot for cold code as its unlikely to be in the cache. A microbenchmark is setup in a way that masks both of these issues pretty well because the work is broken up enough to not expose the transition penalty but frequent enough to keep the method local constant in the L1 or at worst L2 cache.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can understand the mechanism here, but can't get a quantifiable conclusion here. How can we made the decision whether to use the vector path or not?

Comment on lines +309 to +311
value = (byte)(((value & 0xF0) >>> 4) | ((value & 0x0F) << 4));
value = (byte)(((value & 0xCC) >>> 2) | ((value & 0x33) << 2));
value = (byte)(((value & 0xAA) >>> 1) | ((value & 0x55) << 1));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this can be parallelized a bit and avoid the redundant casting by using a uint result instead and only casting to byte at the end

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I performed a simple benchmark on following versions:

        [Benchmark]
        [Arguments(0x12345678u)]
        public uint Reverse1(uint value)
        {
            value = ((value & 0xF0F0F0F0) >>> 4) | ((value & 0x0F0F0F0F) << 4);
            value = ((value & 0xCCCCCCCC) >>> 2) | ((value & 0x33333333) << 2);
            value = ((value & 0xAAAAAAAA) >>> 1) | ((value & 0x55555555) << 1);
            return BinaryPrimitives.ReverseEndianness(value);
        }

        [Benchmark]
        [Arguments(0x12345678u)]
        public uint Reverse2(uint value)
        {
            value = ((value & 0xF0F0F0F0) >>> 4) | ((value & 0x0F0F0F0F) << 4);
            value = ((value & 0x88888888) >>> 3) | ((value & 0x44444444) >>> 1) | ((value & 0x22222222) << 1) | ((value & 0x11111111) << 3);
            return BinaryPrimitives.ReverseEndianness(value);
        }

The first version has longer dependency chain and the second version has one more OR operation. Benchmark shows the second version as slightly slower in unrolled loop.

Copilot AI lite review requested due to automatic review settings August 19, 2026 06:34

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds a new IBinaryInteger<TSelf>.ReverseBits(TSelf) API (with a default interface implementation) and wires up optimized ReverseBits implementations for the built-in integer types, along with corresponding generic-math test coverage (including BigInteger).

Changes:

  • Add static virtual TSelf ReverseBits(TSelf value) to IBinaryInteger<TSelf> with a DIM-based fallback implementation.
  • Implement ReverseBits on the primitive integer types (and Int128/UInt128, nint/nuint), using hardware intrinsics when available and software fallbacks otherwise.
  • Add/extend generic-math tests to validate ReverseBits across the supported numeric types, including BigInteger.

Reviewed changes

Copilot reviewed 32 out of 32 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/libraries/System.Private.CoreLib/src/System/Numerics/IBinaryInteger.cs Adds the ReverseBits DIM fallback implementation on IBinaryInteger<TSelf>.
src/libraries/System.Runtime/ref/System.Runtime.cs Updates System.Runtime ref surface for the new public ReverseBits APIs and interface member.
src/libraries/System.Runtime.Numerics/ref/System.Runtime.Numerics.cs Updates numerics ref surface to include BigInteger’s IBinaryInteger<BigInteger>.ReverseBits.
src/libraries/System.Private.CoreLib/src/System/Byte.cs Adds byte.ReverseBits implementation (intrinsics + fallback).
src/libraries/System.Private.CoreLib/src/System/SByte.cs Adds sbyte.ReverseBits implementation (intrinsics + fallback).
src/libraries/System.Private.CoreLib/src/System/UInt16.cs Adds ushort.ReverseBits implementation (intrinsics + fallback).
src/libraries/System.Private.CoreLib/src/System/Int16.cs Adds short.ReverseBits implementation (intrinsics + fallback).
src/libraries/System.Private.CoreLib/src/System/UInt32.cs Adds uint.ReverseBits implementation (intrinsics + fallback).
src/libraries/System.Private.CoreLib/src/System/Int32.cs Adds int.ReverseBits implementation (intrinsics + fallback).
src/libraries/System.Private.CoreLib/src/System/UInt64.cs Adds ulong.ReverseBits implementation (intrinsics + fallback).
src/libraries/System.Private.CoreLib/src/System/Int64.cs Adds long.ReverseBits implementation (intrinsics + fallback).
src/libraries/System.Private.CoreLib/src/System/UIntPtr.cs Adds nuint.ReverseBits forwarding to uint/ulong.ReverseBits by target bitness.
src/libraries/System.Private.CoreLib/src/System/IntPtr.cs Adds nint.ReverseBits forwarding to int/long.ReverseBits by target bitness.
src/libraries/System.Private.CoreLib/src/System/UInt128.cs Adds UInt128.ReverseBits (GFNI path + scalar composition).
src/libraries/System.Private.CoreLib/src/System/Int128.cs Adds Int128.ReverseBits (GFNI path + scalar composition).
src/libraries/System.Private.CoreLib/src/System/Char.cs Adds explicit IBinaryInteger<char>.ReverseBits forwarding via ushort.ReverseBits.
src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs Adds IBinaryInteger<BigInteger>.ReverseBits implementation for BigInteger.
src/libraries/System.Runtime.Numerics/tests/BigIntegerTests.GenericMath.cs Adds ReverseBits tests for BigInteger via BinaryIntegerHelper<>.
src/libraries/Common/tests/System/GenericMathHelpers.cs Extends BinaryIntegerHelper<TSelf> with a ReverseBits forwarding helper.
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/ByteTests.GenericMath.cs Adds ReverseBitsTest for byte.
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/SByteTests.GenericMath.cs Adds ReverseBitsTest for sbyte.
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/CharTests.GenericMath.cs Adds ReverseBitsTest for char.
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/UInt16Tests.GenericMath.cs Adds ReverseBitsTest for ushort.
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/Int16Tests.GenericMath.cs Adds ReverseBitsTest for short.
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/UInt32Tests.GenericMath.cs Adds ReverseBitsTest for uint.
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/Int32Tests.GenericMath.cs Adds ReverseBitsTest for int.
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/UInt64Tests.GenericMath.cs Adds ReverseBitsTest for ulong.
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/Int64Tests.GenericMath.cs Adds ReverseBitsTest for long.
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/UInt128Tests.GenericMath.cs Adds ReverseBitsTest for UInt128.
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/Int128Tests.GenericMath.cs Adds ReverseBitsTest for Int128.
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/UIntPtrTests.GenericMath.cs Adds ReverseBitsTest for nuint with 32/64-bit expected values.
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/IntPtrTests.GenericMath.cs Adds ReverseBitsTest for nint with 32/64-bit expected values.
Suppressed comments (1)

src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs:3562

  • Once the buffer is tracked by a using var (see earlier), this explicit Dispose becomes redundant and easy to forget if new early-returns/throws are added.
            BigInteger result = new BigInteger(byteBuffer, isBigEndian: !BitConverter.IsLittleEndian);

            rentedBuffer.Dispose();

Comment on lines +3489 to +3491
int MSBstrip = 0;
// First handle round-tripping for the extra trailing word
// 33 bits differ from sign.
Copilot AI review requested due to automatic review settings August 19, 2026 15:46

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 32 out of 32 changed files in this pull request and generated no new comments.

Suppressed comments (5)

src/libraries/System.Private.CoreLib/src/System/Numerics/IBinaryInteger.cs:424

  • The stackalloc path always allocates 256 bytes even when byteCount is much smaller, which increases per-call stack usage for most primitive types (where GetByteCount() is typically 1–16/32). Consider stackalloc’ing byteCount (while keeping the threshold decision) to reduce stack pressure.
            const int StackallocThreshold = 256;

            int byteCount = value!.GetByteCount();
            byte[]? rented = null;
            Span<byte> bytes = byteCount <= StackallocThreshold
                ? stackalloc byte[StackallocThreshold]
                : rented = ArrayPool<byte>.Shared.Rent(byteCount);
            bytes = bytes.Slice(0, byteCount);

src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs:3563

  • rentedBuffer.Dispose() is not in a finally/using scope. If the BigInteger constructor throws (even unexpectedly, e.g., OOM), the rented buffer may not be returned/disposed. Consider wrapping the post-rent logic so rentedBuffer.Dispose() is guaranteed to run.
            // Let the constructor to strip any redundant bits
            BigInteger result = new BigInteger(byteBuffer, isBigEndian: !BitConverter.IsLittleEndian);

            rentedBuffer.Dispose();

src/libraries/System.Runtime/tests/System.Runtime.Tests/System/UInt128Tests.GenericMath.cs:283

  • This is inside UInt128’s ReverseBitsTest, but it asserts BinaryIntegerHelper<ulong>.ReverseBits(...). This looks like a copy/paste mistake and weakens coverage of the UInt128 implementation. Consider removing this line or converting it into an assertion against BinaryIntegerHelper<UInt128>.ReverseBits(...).
            Assert.Equal(0x80402010_08040201, BinaryIntegerHelper<ulong>.ReverseBits(0x80402010_08040201));

src/libraries/System.Runtime/tests/System.Runtime.Tests/System/Int128Tests.GenericMath.cs:284

  • This is inside Int128’s ReverseBitsTest, but it asserts BinaryIntegerHelper<ulong>.ReverseBits(...). This appears to be an accidental ulong assertion in the wrong test suite. Consider removing it or replacing it with an Int128-specific assertion.
            Assert.Equal(0x80402010_08040201, BinaryIntegerHelper<ulong>.ReverseBits(0x80402010_08040201));

src/libraries/System.Private.CoreLib/src/System/UIntPtr.cs:337

  • nuint/nint bit-manipulation APIs in these files are often annotated with [Intrinsic] (e.g., PopCount, RotateLeft/Right) to help the JIT recognize and optimize patterns. If this method is intended to be treated similarly, consider adding [Intrinsic] for consistency and potential codegen benefits.
        /// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)"/>
        public static nuint ReverseBits(nuint value)

Copilot stopped reviewing on behalf of huoyaoyuan due to an error August 19, 2026 16:07
Copilot AI review requested due to automatic review settings August 19, 2026 16:08

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 32 out of 32 changed files in this pull request and generated no new comments.

Suppressed comments (2)

src/libraries/System.Runtime/tests/System.Runtime.Tests/System/UInt128Tests.GenericMath.cs:283

  • This assertion is testing ulong bit-reversal inside the UInt128 test file, duplicating coverage already present in UInt64Tests.GenericMath and making this test less focused on UInt128 behavior. Consider removing it and keeping only UInt128-specific cases here.
            Assert.Equal(0x80402010_08040201, BinaryIntegerHelper<ulong>.ReverseBits(0x80402010_08040201));

src/libraries/System.Runtime/tests/System.Runtime.Tests/System/Int128Tests.GenericMath.cs:284

  • This assertion is exercising ulong bit-reversal inside the Int128 test file, duplicating the UInt64Tests.GenericMath coverage and making this test less focused on Int128 behavior. Consider removing it.
            Assert.Equal(0x80402010_08040201, BinaryIntegerHelper<ulong>.ReverseBits(0x80402010_08040201));

Copilot AI review requested due to automatic review settings August 24, 2026 06:13

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 32 out of 32 changed files in this pull request and generated 4 comments.

Copilot AI review requested due to automatic review settings August 24, 2026 06:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 32 out of 32 changed files in this pull request and generated no new comments.

Suppressed comments (7)

Previously missed (7) — in code that hasn't changed since the last review.

src/libraries/System.Private.CoreLib/src/System/UInt32.cs:330

  • ReverseBits is the same kind of bit-operation helper as LeadingZeroCount/PopCount/Rotate* in this file, but it isn't marked [Intrinsic]. The approved proposal text also calls out [Intrinsic] for future JIT intrinsification, so this should likely be consistent with the other helpers here.
        /// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)"/>
        public static uint ReverseBits(uint value)
        {

src/libraries/System.Private.CoreLib/src/System/Int32.cs:317

  • ReverseBits is missing [Intrinsic] even though the other core bit-operation helpers in this type are annotated (e.g., LeadingZeroCount, PopCount, Rotate*). If this is intended to be a JIT intrinsic in the future, it should be marked consistently here.
        /// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)"/>
        public static int ReverseBits(int value)
        {

src/libraries/System.Private.CoreLib/src/System/UInt64.cs:337

  • ReverseBits is missing [Intrinsic] while neighboring PopCount/Rotate* helpers are [Intrinsic]. Marking it would keep the API consistent and aligns with the linked proposal's expectation of [Intrinsic] for potential JIT recognition.
        /// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)"/>
        public static ulong ReverseBits(ulong value)
        {

src/libraries/System.Private.CoreLib/src/System/Int64.cs:314

  • ReverseBits is missing the [Intrinsic] annotation used for other fundamental bit operations in this file. If the intent is future JIT intrinsification, it should be annotated consistently.
        /// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)"/>
        public static long ReverseBits(long value)
        {

src/libraries/System.Private.CoreLib/src/System/IntPtr.cs:347

  • nint.ReverseBits is the native-size counterpart of the other [Intrinsic] bit helpers on IntPtr (e.g., PopCount, Rotate*), but it isn't marked [Intrinsic]. Adding it would keep the pattern consistent and avoids it being "the odd one out" in this section.
        /// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)"/>
        public static nint ReverseBits(nint value)
        {

src/libraries/System.Private.CoreLib/src/System/UIntPtr.cs:339

  • nuint.ReverseBits sits alongside other [Intrinsic] helpers (LeadingZeroCount, PopCount, Rotate*), but it isn't annotated [Intrinsic]. Even if it stays as a wrapper, marking it would keep this section consistent.
        /// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)"/>
        public static nuint ReverseBits(nuint value)
        {

src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs:3453

  • The linked approved-API issue's top post currently states "BigInteger uses the DIM" (minimal two's complement byte representation), but this PR adds a substantial BigInteger-specific implementation with a different goal (explicit 32-bit semantics + round-tripping invariants). That might be the right behavior, but it should be reconciled with the issue/proposal text (or explicitly called out in the PR description) so the intended BigInteger semantics are clear to reviewers and API consumers.
        /// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)" />
        static BigInteger IBinaryInteger<BigInteger>.ReverseBits(BigInteger value)
        {
            // Reversing bits makes little sense to BigInteger which is effectively infinite.
            // Only ensure a proper round-tripping behavior.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.Numerics community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[API Proposal]: BitOperations.ReverseBits

4 participants