2012-07-22 34 views
2

您好我想使用自定義的二進制整數劃分方法: 來源: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; 
} 
  • 不過我有2個問題:

1)我想用它32位整數不是Int128。所以我假定Int128應由INT代替,並且所述(INT I = 0; 我< 128;我++)應該由代替我< 32;。正確?

2)remainder._lo | = 1 - >這行在C#中完全不起作用。我想這與它使用的自定義128位int結構有關,我不知道它是做什麼的。有人可以幫我解決這個問題,並翻譯它,以便它與int32?

編輯:只是爲了澄清我知道什麼是位運算符做,問題部分是這樣的: remainder._lo。我不知道這個屬性是指什麼,不確定這個行的目的,以及它如何轉換爲int32?

+0

你是什麼意思「在C#中完全不工作」?比特明智的運營商還活着,以及...你看到了什麼?你使用的是「int」而不是定製結構,那麼確實:沒有.lo會被定義,但是...... – 2012-07-22 11:58:32

+0

是的,這個問題源於他們使用不可用的128位int結構,它具有「_lo 」。本機的32位int沒有,我不知道該行發生了什麼! – 2012-07-22 12:00:29

回答

0
  1. 要使用32位整數(System.Int32),您可以用INT替代Int128並在128 for循環與32使用它 - 因此,這是正確的。

  2. _lo屬性只是128位數的低64位。它是用來因爲在.NET中的最大的整數類型是64位(System.Int64) - 因此,與32位你可以省略屬性:
    remainder |= 1;

如果你按照你在你的問題給出的鏈接,並回到幾頁後,你會發現Int128結構的實際實現。它開始here

+0

這是一篇寫得很好的文章。謝謝! – 2012-07-22 13:07:16

0

它在引導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次。