Skip to content

Add System.Math.DivRem for ulong and other integers #42156

@Maykeye

Description

@Maykeye

Background and Motivation

Math.DivRem currently accepts only int32 and int64. When you are working with uint64, as of now it's easier to calculate division and remainder "by hand".
Which is not only surprising and slightly inconvenient, but it also may lead to suboptimal code if you are not aware of #5213

So for convenience I suggest adding DivRem for uint64 and since, these integers are not special, add for all other integer types while we are at it: uint32, [u]int16, [s]byte

Proposed API

namespace System
{
    public static partial class Math
    {
+          public static ulong DivRem(ulong a, ulong b, out ulong result)
+          public static uint DivRem(uint a, uint b, out uint result)
+          public static ushort DivRem(ushort a, ushort b, out ushort result)
+          public static short DivRem(short a, short b, out short result)
+          public static byte DivRem(byte a, byte b, out byte result)
+          public static sbyte DivRem(sbyte a, sbyte  b, out sbyte result)
          public static int DivRem(int a, int b, out int result)
     }

Usage Examples

Personally I ran into it when tried to use the function while formatting bit address inside of really large address space:

            bytes = Math.DivRem(bitOffset, 8ul, out bits);
            Console.WriteLine($"{bytes}+({bits}b)");

However looking for duplicates, I noticed that ulongs are implemented already(just not exposed), so here is the usage example from the very this exact repo.

Risks

There might be confusion what is called due to implicit conversions(when a=b=short, result=int)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions