Home > database >  Why BigInteger.ToByteArray return a single-item array instead of a multi-item array?
Why BigInteger.ToByteArray return a single-item array instead of a multi-item array?

Time:03-04

Why convert a byte array to BigInteger, If all members submit 0 or 255 the result is a single-item array instead of a multi-item array? for example:

        byte[] byteArray = { 0, 0, 0, 0 };
        BigInteger newBigInt = new BigInteger(byteArray);
        MessageBox.Show(newBigInt.ToString());
        byte[] bytes;
        bytes = newBigInt.ToByteArray();
        MessageBox.Show(string.Join(", ", bytes));

This code return only one zero instead of an array of four zeros. The same is true for the 255. Does anyone know why while another output array with similar items are converted separately?

CodePudding user response:

BigIngteger doesn't waste space on redundant leading values. If all the individual byte values are zero, that makes the entire number zero which can be represented as a single byte with value zero. So 0000 is the same value as 0.

If all values are 255, that represents 0xFFFFFFFF or -1 since it's a signed integer. And since -1 can be represented as 0xFF, 0xFFFF, 0xFFFFFF etc., there's no point in keeping those redundant leading bytes.

CodePudding user response:

BigInteger uses a variable length encoding to represent a number. It has to, since it needs to represent arbitrary large integers.

This is specified in the documentation to ToByteArray

Returns the value of this BigInteger as a byte array using the fewest number of bytes possible. If the value is zero, returns an array of one byte whose element is 0x00.

...

Negative values are written to the array using two's complement representation in the most compact form possible. For example, -1 is represented as a single byte whose value is 0xFF instead of as an array with multiple elements, such as 0xFF, 0xFF or 0xFF, 0xFF, 0xFF, 0xFF.

See also Variable Length Quantity/LEB128 for other kinds of variable length encodings used in some protocols.

  • Related