I'm converting a byte[]
to a BigInteger
and I want to ensure it comes out positive. The docs say:
To prevent positive values from being misinterpreted as negative values, you can add a zero-byte value to the end of the array.
But it doesn't specify how. So, how can I do this?
Found this to be the simplest:
public static BigInteger UnsignedBigInt(byte[] bytes)
{
if ((bytes[bytes.Length - 1] & 0x80) != 0) Array.Resize(ref bytes, bytes.Length + 1);
return new BigInteger(bytes);
}
Thanks dtb
Try this:
byte[] bytes = ...
if ((bytes[bytes.Length - 1] & 0x80) != 0)
{
Array.Resize<byte>(ref bytes, bytes.Length + 1);
}
BigInteger result = new BigInteger(bytes);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With