0

So in c#, I have needed a random below given number generator and I found one on StackOverFlow. But near the end, it converts the byte array into a BigInteger. I tried doing the same, though I am using the Deveel-Math lib as it allows me to us BigDeciamals. But I have tried to the array change into a value, and that into a String but I keep getting a "Could not find any recognizable digits." error and as of now I am stumped.

public static BigInteger RandomIntegerBelow1(BigInteger N)
    {
        byte[] bytes = N.ToByteArray();
        BigInteger R;
        Random random = new Random();

        do
        {
            random.NextBytes(bytes);
            bytes[bytes.Length - 1] &= (byte)0x7F; //force sign bit to positive

            R = BigInteger.Parse(BytesToStringConverted(bytes)) ;
           //the Param needs a String value, exp: BigInteger.Parse("100")
        } while (R >= N);

        return R;
    }
    static string BytesToStringConverted(byte[] bytes)
    {
        using (var stream = new MemoryStream(bytes))
        {
            using (var streamReader = new StreamReader(stream))
            {
                return streamReader.ReadToEnd();
            }
        }
    }

Deveel-Math

Community
  • 1
  • 1
no name
  • 72
  • 6

1 Answers1

1

Wrong string conversion

You are converting your byte array to a string of characters based on UTF encoding. I'm pretty sure this is not what you want.

If you want to convert a byte array to a string that contains a number expressed in decimal, try this answer using BitConverter.

if (BitConverter.IsLittleEndian)
    Array.Reverse(array); //need the bytes in the reverse order
int value = BitConverter.ToInt32(array, 0);

This is way easier

On the other hand, I notice that Deveel-Math's BigInteger has a constructor that takes a byte array as input (see line 226). So you should be able to greatly simplify your code by doing this:

R = new Deveel.Math.BigInteger(1, bytes) ;

However, since Deveel.Math appears to be BigEndian, you may need to reverse the array first:

System.Array.Reverse(bytes);
R = new Deveel.Math.BigInteger(1, bytes);
Community
  • 1
  • 1
John Wu
  • 50,556
  • 8
  • 44
  • 80
  • No I'm not using the built in Math class I'm using an open source math lib called Deveel-Math. In addition I'm still lost on how to use the first method of conversion. where do I implement it? – no name Feb 21 '17 at 23:29
  • Modified to accomodate Deveel-Math's class. – John Wu Feb 21 '17 at 23:43
  • I get these options only though: https://gyazo.com/194f60bae0b9a56ad44b0b8e0ad00f96 – no name Feb 21 '17 at 23:50
  • Don't use the static `Parse` method. Type `new BigInteger(` and see what comes up. – John Wu Feb 21 '17 at 23:58