Search code examples
c#performancebigintegertwos-complementbitconverter

Why does BitConverter shrink my already allocated array? (I'm trying to prevent a two's complement issue)


I am allocating an array that is intentionally bigger than the result of BitConverter.GetBytes. My goal is to leave the last byte empty so that I can prevent this number from being seen as the two's compliment and have tempPosBytes2[

When I run BitConverter.GetBytes my array tempPosBytes2 seems to shrink.

uint positiveNumber = 4293967296;
byte[] tempPosBytes2 = new byte[tempPosBytes.Length + 1]; // four bytes plus one
tempPosBytes2 = BitConverter.GetBytes(positiveNumber);  // tempPositiveBytes2 is now 4 bytes!!

Question

What is going on under the covers, and how can I leave the trailing byte without copying the array?

I need this to work with BigInteger(byte[]) as in the following:

BigInteger positiveBigIntBAD2 = new BigInteger(tempPosBytes2); // Invalid

Solution

  • Your array isn't being shrunk, you have an entirely new array allocated inside BitConverter.GetBytes.

    Of course you can copy that output data into an array with size of your choice.

    Or, just make your own version of BitConverter. It's really simple:

    byte[] tempPosBytes2 = new byte[] { (byte)(positiveNumber), 
                                        (byte)(positiveNumber >> 8), 
                                        (byte)(positiveNumber >> 16), 
                                        (byte)(positiveNumber >> 24), 
                                        0 };
    

    I suggest you compare the performance using both techniques.

    BTW, you could just use the BigInteger constructor that takes a uint.