c# - 自定义二进制除法?

标签 c# binary integer-division

您好,我正在尝试使用自定义二进制整数除法: 来源:http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=642

public static void DivMod (Int128 dividend, Int128 divisor, out Int128 quotient, out  Int128 remainder)
{
// Determine the sign of the results and make the operands positive.
int remainderSign = 1;
int quotientSign = 1;
if (dividend < 0)
{
    dividend = -dividend;
    remainderSign = -1;
}
if (divisor < 0)
{
    divisor = -divisor;
    quotientSign = -1;
}
quotientSign *= remainderSign;

quotient = dividend;
remainder = 0;
for (int i = 0; i < 128; i++)
{
    // Left shift Remainder:Quotient by 1
    remainder <<= 1;
    if (quotient < 0)
        remainder._lo |= 1;
    quotient <<= 1;

    if (remainder >= divisor)
    {
        remainder -= divisor;
        quotient++;
    }
}

// Adjust sign of the results.
quotient *= quotientSign;
remainder *= remainderSign;
}
  • 但是我有两个问题:

1) 我想将它用于 32 位整数而不是 Int128。所以我假设 Int128 应该替换为 int,并且 (int i = 0; i < 128; i++) 应该替换通过 i < 32;。正确吗?

2) remainder._lo |= 1 -> 此行在 C# 中根本不起作用。我想这与他们使用的自定义 128 位 int 结构有关,但我不知道它的用途。有人可以帮我解决这个问题,并翻译它以便它适用于 int32 吗?

编辑: 只是为了澄清我知道按位运算符的作用,问题部分是这样的: 剩余._lo。我不知道这个属性指的是什么,也不确定这一行的用途,以及如何将其转换为 int32?

最佳答案

  1. 要将它用于 32 位整数 (System.Int32),您可以将 Int128 替换为 int,并将 for 循环中的 128 替换为 32 - 所以这是正确的。

  2. _lo 属性只是 128 位数字的低 64 位。使用它是因为 .NET 中最大的整数类型是 64 位 (System.Int64) - 因此对于 32 位你可以省略属性:
    余数 |= 1;

如果您点击您在问题中提供的链接并返回几页,您将找到 Int128 结构的实际实现。它开始 here .

关于c# - 自定义二进制除法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11599993/

相关文章:

c# - 我可以使用 C# WinForm 模拟此选项对话框窗口吗?

java - 如何使用模数划分?

c# - 除整数类型 - 结果是否可预测?

c# - 使用异步方法选择

c# - ASP.Net-Core 选项验证

java - 将位数组值转换为二进制数字符串

algorithm - 非还原除法算法

c++ - 将文件读入结构 (C++)

java - Java中的整数除法

c# - 处理存储在公共(public)静态字段中的 IDisposable 对象