Hi I am trying to use the custom Binary Integer division method:
Source: 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;
}
- However I have 2 problems:
1) I would like to use it for 32 bit integers not Int128. so I assume that the Int128 should be replaced by int, and the (int i = 0; i < 128; i++) should be replaced by i < 32;. Correct?
2) remainder._lo |= 1 -> this line does not work at all in C#. I suppose it has to do with that custom 128bit int struct they use, and I have no idea what it is meant to do. Can somebody help me out with this one, and translate it so that it works with int32?
EDIT: just to clarify I know what the bitwise operators do, the problem part is this:
remainder._lo. I dont know what this property refers to, and not sure of the purpose of this line, and how it would be translated to an int32?
To use it with 32 bit integer (
System.Int32) you can replace Int128 with int and the 128 in the for loop with 32 – So this is correct.The
_loproperty is just the lower 64 bits of the 128 bits number. It is used because the biggest integer type in .NET is 64 bits (System.Int64) – So with 32 bits you can just omit the property:remainder |= 1;If you follow the link you gave in your question and go back a few pages you will find the actual implementation of the
Int128struct. It starts here.