【问题标题】:Custom Binary Division?自定义二进制除法?
【发布时间】:2012-07-22 11:43:29
【问题描述】:

您好我正在尝试使用自定义二进制整数除法方法: 来源: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 ; i++) 应该替换由 i 。对吗?

2) remaining._lo |= 1 -> 这一行在 C# 中根本不起作用。我想这与他们使用的自定义 128 位 int 结构有关,我不知道它是什么意思。有人可以帮我解决这个问题,并翻译它以使其与 int32 一起使用吗?

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

【问题讨论】:

  • “在 C# 中根本不起作用”是什么意思?位明智的运营商活得很好......你看到了什么?你们使用“int”而不是自定义结构,那么确实:不会定义 .lo,但是...
  • 是的,问题源于他们使用了一个不可用的 128 位 int 结构,该结构具有“_lo”属性。原生 32 位 int 没有,我不知道那一行发生了什么!

标签: c# binary integer-division


【解决方案1】:
  1. 要将其与 32 位整数 (System.Int32) 一起使用,您可以将 Int128 替换为 int,将 for 循环中的 128 替换为 32 - 所以这是正确的。

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

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

【讨论】:

  • 这是一个写得很好的答案。谢谢!
【解决方案2】:

在指南的this page上有说明:

public struct Int128 : IComparable, IFormattable, IConvertible, IComparable<Int128_done>, IEquatable<Int128_done>

{
  private ulong _lo;
  private long _hi;

  public Int128(UInt64 low, Int64 high)
  {
    _lo = low;
    _hi = high;
  }
}

你可以用 32 位整数忽略它,只做some32int |= 1

他说每个位循环一次,所以对于 32 位整数,你只能循环 32 次。

【讨论】:

    猜你喜欢
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多