Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么BitConverter会收缩已分配的阵列?(我正在努力防止二的补足问题)_C#_Performance_Biginteger_Twos Complement_Bitconverter - Fatal编程技术网

C# 为什么BitConverter会收缩已分配的阵列?(我正在努力防止二的补足问题)

C# 为什么BitConverter会收缩已分配的阵列?(我正在努力防止二的补足问题),c#,performance,biginteger,twos-complement,bitconverter,C#,Performance,Biginteger,Twos Complement,Bitconverter,我分配的数组故意大于BitConverter.GetBytes的结果。我的目标是将最后一个字节留空,这样我就可以防止这个数字被视为这两个人的赞美,并让tempPosBytes2[ 当我运行BitConverter.GetBytes时,我的数组tempPosBytes2似乎在收缩 uint positiveNumber = 4293967296; byte[] tempPosBytes2 = new byte[tempPosBytes.Length + 1]; // four bytes plus

我分配的数组故意大于BitConverter.GetBytes的结果。我的目标是将最后一个字节留空,这样我就可以防止这个数字被视为这两个人的赞美,并让tempPosBytes2[

当我运行BitConverter.GetBytes时,我的数组tempPosBytes2似乎在收缩

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

封面下发生了什么,如何在不复制数组的情况下保留尾随字节

我需要它来处理BigIntegerbyte[],如下所示:

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

您的数组没有缩小,您在BitConverter.GetBytes中分配了一个全新的数组

当然,您可以将输出数据复制到您选择大小的数组中

或者,只需制作自己版本的BitConverter。它非常简单:

byte[] tempPosBytes2 = new byte[] { (byte)(positiveNumber), 
                                    (byte)(positiveNumber >> 8), 
                                    (byte)(positiveNumber >> 16), 
                                    (byte)(positiveNumber >> 24), 
                                    0 };
我建议您使用这两种技术来比较性能

顺便说一句,您可以使用接受uint的BigInteger构造函数。

BitConverter.GetBytes没有使用数组,它不能使用,因为您从未传入它

相反,您正在创建一个数组,然后立即销毁它


如果需要将GetBytes的结果放入数组中,您可以查看是否存在重载或其他方法,该方法会将数组中的内容写入或复制到您自己的数组中。

它不会收缩任何内容。GetBytes始终会分配一个新数组,并且您的分配会覆盖对现有字节数组的引用

如果您需要最高字节始终为零,以便BigInteger不会将其解释为负数,那么您可以在GetBytes之后将大小增加1,新字节的值将为零,就像您所希望的那样

页面上有一个例子讨论了这一点,它提供了一个只会在必要时调整数组大小的例子。您可以自己编写一个助手方法CreateUnsignedBigIntegerbyte[],它可以完成这一任务

public BigInteger CreateUnsignedBigInteger(byte[] bytes)
{
    if ((bytes[bytes.Length - 1] & 0x80) > 0) 
    {
        byte[] old = bytes;
        bytes = new byte[old.Length + 1];
        Array.Copy(old, bytes, old.Length);
    }

    return new BigInteger(bytes);
}

具有讽刺意味的是,如果您想要一个字节[],可以将其传递到BigInteger构造函数中,以给出与uint等价的值,那么您可以这样做

byte[] tempPosBytes = new BigInteger(positiveNumber).ToByteArray();

我考虑过调整大小,但这是一个On操作,其中n是对象的大小array@makerofthings7:你在这个数组上执行的所有其他操作也是如此。n很小。是的,它是开的,但n是四。我们知道它是四,因为你处理的是32位整数。这只是一个例子……我的实字节数组更大,我正在尝试解决e是一个更大的问题。我认为我的核心问题是两者的互补。请参阅edit以获取仅在必要时调整数组大小的帮助方法,并封装BigInteger的调整大小和创建。