문제

I am trying to understand why BigInteger is throwing an overflow exception. I tried to visualize this by converting the BigInteger to a byte[] and iteratively incrementing the shift until I see where the exception occurs.

  • Should I be able to bit-shift >> a byte[], or is C# simply not able to?

Code causing an exception

        uint amountToShift2 = 12;
        BigInteger num = new BigInteger(-126);
        uint  compactBitsRepresentation = (uint)(num >> (int)amountToShift2);
도움이 되었습니까?

해결책

Regarding your edited question with:

uint amountToShift2 = 12;
BigInteger num = new BigInteger(-126);
uint compactBitsRepresentation = (uint)(num >> (int)amountToShift2);

The bit shift works OK and produces a BigInteger of value -1 (negative one).

But the conversion to uint throws an exception becauce -1 is outside the range of an uint. The conversion from BigInteger to uint does not "wrap around" modulo 2**32, but simply throws.

You can get around that with:

uint compactBitsRepresentation = (uint)(int)(num >> (int)amountToShift2);

which will not throw in unchecked context (which is the usual context).

다른 팁

There is no >> or << bit-shift operators for byte arrays in C#. You need to write code by hand to do so (pay attention to bits that fall off).

Something tells me that the >> operator won't work with reference types like arrays, rather it works with primitive types.

your ints are actually represented by a series of bytes, so say

int i = 6;

i is represented as

00000000000000000000000000000110

the >> shifts all the bits to the right, changing it to

00000000000000000000000000000011

or 3


If you really need to shift the byte array, it shouldn't be too terribly hard to define your own method to move all the items of the array over 1 slot. It will have O(n) time complexity though.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top