字节到值错误
Byte to value error
所以在 c# 中,我需要一个低于给定数字的随机生成器,我在 Whosebug 上找到了一个。但接近尾声时,它将字节数组转换为 BigInteger。我尝试做同样的事情,尽管我使用的是 Deveel-Math 库,因为它允许我使用 BigDeciamals。但是我已经尝试将数组更改为一个值,然后将其更改为一个字符串,但我一直收到 "Could not find any recognizable digits." 错误,到目前为止我很困惑。
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();
}
}
}
错误的字符串转换
您正在将字节数组转换为基于 UTF 编码的字符串。我很确定这不是你想要的。
如果要将字节数组转换为包含以十进制表示的数字的字符串,请尝试 this answer using BitConverter。
if (BitConverter.IsLittleEndian)
Array.Reverse(array); //need the bytes in the reverse order
int value = BitConverter.ToInt32(array, 0);
这样简单多了
另一方面,我注意到 Deveel-Math's BigInteger 有一个将字节数组作为输入的构造函数(请参阅第 226 行)。所以你应该能够通过这样做大大简化你的代码:
R = new Deveel.Math.BigInteger(1, bytes) ;
但是,由于 Deveel.Math 看起来是 BigEndian,您可能需要先反转数组:
System.Array.Reverse(bytes);
R = new Deveel.Math.BigInteger(1, bytes);
所以在 c# 中,我需要一个低于给定数字的随机生成器,我在 Whosebug 上找到了一个。但接近尾声时,它将字节数组转换为 BigInteger。我尝试做同样的事情,尽管我使用的是 Deveel-Math 库,因为它允许我使用 BigDeciamals。但是我已经尝试将数组更改为一个值,然后将其更改为一个字符串,但我一直收到 "Could not find any recognizable digits." 错误,到目前为止我很困惑。
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();
}
}
}
错误的字符串转换
您正在将字节数组转换为基于 UTF 编码的字符串。我很确定这不是你想要的。
如果要将字节数组转换为包含以十进制表示的数字的字符串,请尝试 this answer using BitConverter。
if (BitConverter.IsLittleEndian)
Array.Reverse(array); //need the bytes in the reverse order
int value = BitConverter.ToInt32(array, 0);
这样简单多了
另一方面,我注意到 Deveel-Math's BigInteger 有一个将字节数组作为输入的构造函数(请参阅第 226 行)。所以你应该能够通过这样做大大简化你的代码:
R = new Deveel.Math.BigInteger(1, bytes) ;
但是,由于 Deveel.Math 看起来是 BigEndian,您可能需要先反转数组:
System.Array.Reverse(bytes);
R = new Deveel.Math.BigInteger(1, bytes);