dotnet / dotnet/dotnet-api-docs
The documentation of BigInteger.RightShift describes an algorithm that is supposed to be equivalent to this operator, but this does not seem to be the case
- Dominant language
- C#
- Stars
- 949
- Forks
- 1.7k
- Avg merge
- 3d 27m
- Merged PRs (30d)
- 49
Description
From [BigInteger.RightShift(BigInteger, Int32) Operator § Remarks](https://docs.microsoft.com/en-us/dotnet/api/system.numerics.biginteger.op_rightshift?view=net-6.0#remarks):
> Languages that do not support custom operators can perform a bitwise right-shift operation by dividing value by BigInteger.Pow(2, shift) and subtracting 1 times shift for negative values. The following example shows that the results are identical to the results of using this operator.
The documentation elaborates that for any BigInteger number and int ctr the following two pieces of code should be equivalent:
```csharp
BigInteger newNumber = number >> ctr;
```
and:
```csharp
BigInteger newNumber = BigInteger.Divide(number, BigInteger.Pow(2, ctr));
if (newNumber * ctr < 0)
newNumber--;
```
This does not seem to be the case.
Let me provide a counterexample:
```csharp
using System.Numerics;
BigInteger number = -16;
int ctr = 2;
BigInteger newNumber1 = number >> ctr;
Console.WriteLine(" {0,2} bits: {1,35} {2,30}", ctr, newNumber1, newNumber1.ToString("X"));
BigInteger newNumber2 = BigInteger.Divide(number, BigInteger.Pow(2, ctr));
if (newNumber2 * ctr < 0)
newNumber2--;
Console.WriteLine(" {0,2} bits: {1,35} {2,30}", ctr, newNumber2, newNumber2.ToString("X"));
```
The output of the above program is:
```
2 bits: -4 C
2 bits: -5 B
```
-16 is represented as `11110000`. Right shifting this number two positions gives `11111100`, which represents -4, which is -16 / 2^2. No substraction is necessary nor correct in this situation.
This aside, the prose description of the algorithm that is supposed to be equivalent to the right shift operator does not match the actual algorithm, as presented in the C# snippet. The prose description calls to substract 1 times shift for negative values (presumably of the original number), while the actual algorithm substract 1 for negative values of the number being shifted times shift.
Contributor guide
Assessment
This issue has not been assessed yet.