Skip to content

Provide a way to perform Add with carry and Subtract with borrow #48247

@Scooletz

Description

@Scooletz

Background and Motivation

The motivation behind this proposal is to provide API that can be useful for adding/subtracting big integers without the need of calculating carry manually. Currently, the only way that I'm aware of .NET uses ADC assembly instruction is an overflow check, followed by a conditional jump to the exception throw. With a proper intrinsics/Math method it could be leveraged to provide a fast add with carry operation. This would be beneficial for BitInteger but also for any other code using this API.

Proposed API

namespace System
{
    public static partial class Math
    {
+         ulong AddWithCarry(ulong a, ulong b, ref ulong carry);
    }
 }

Usage Examples

The immediate beneficent would be BigInteger with methods like

for (; i < rightLength; i++)
{
long digit = (left[i] + carry) + right[i];
bits[i] = unchecked((uint)digit);
carry = digit >> 32;

Risks

The implementation overhead. This would require to go to JIT/intrinsics area and provide a proper fallback, something similar to what was done in Math.BigMul.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions