-1

I would like to know if there is any efficient way to store a big number using C#. I would like to create number consisting of 960 bytes but BigInteger can't hold it. I would be grateful for any advice.

UPDATE: I am using random byte generator to fill up array needed for constructor of BigInteger. For 960 byte array i BigInteger is returning a negative number.

Dago
  • 788
  • 2
  • 9
  • 24

1 Answers1

2
static void Main(string[] args)
{
    var arr = new byte[960];

    for (int i = 0; i != arr.Length; i++)
    {
        arr[i] = byte.MaxValue;
    }

    var big = new BigInteger(arr);
}

is working pretty fine and the result is -1 because the representation of the number is in the two's complement. That means a number with just 1s in binary always resolves to -1 as you can see in the article.


if you add one Length more and set the last element of the array to zero you should get a positive number which represents your binary number (this one byte will not hurt you):

var arr = new byte[961];
arr[arr.Length-1] = 0;
var big2 = new BigInteger(arr);

but then you really should be sure in what format your binary number is and what BigInteger is "reading"

Jens
  • 2,592
  • 2
  • 21
  • 41
  • thanks, indeed it is working ok. I just thought i am getting overflow. – Dago Nov 23 '15 at 15:19
  • on the first five seconds i was also suprised but then i realized the complement. i will also add a solution – Jens Nov 23 '15 at 15:22
  • to sum up. If my BigInteger has a negative sign that means my 960 byte representing a negative number right? – Dago Nov 23 '15 at 15:53
  • @Dago yes. When the MSB (most significant bit) is 1 then your number is negative. That means doing (this sets the MSB to 1): `arr[arr.Length - 1] |= 0b1000 0000` will result always in a negative number. – Jens Nov 24 '15 at 06:16