Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the easiest way to add a zero-byte to a byte array?

Tags:

c#

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

like image 757
mpen Avatar asked Dec 12 '22 22:12

mpen


1 Answers

Try this:

byte[] bytes = ...

if ((bytes[bytes.Length - 1] & 0x80) != 0)
{
    Array.Resize<byte>(ref bytes, bytes.Length + 1);
}

BigInteger result = new BigInteger(bytes);
like image 89
dtb Avatar answered Dec 14 '22 12:12

dtb