Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.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#比特移位&;位运算_C#_Bit Manipulation_Bit Shift - Fatal编程技术网

C#比特移位&;位运算

C#比特移位&;位运算,c#,bit-manipulation,bit-shift,C#,Bit Manipulation,Bit Shift,我正试图找到解决以下问题的更快方法 我有两个表示位的int数组,这里是一个8位数组的例子 int[] intArray1 = new[] {1, 1, 1, 0, 1, 1, 0, 1}; int[] intArray2 = new[] {0, 1, 0, 0, 1, 0, 0, 1}; 阵列中的位数可以是8、32、64和64+ 因此,我应该能够创建一个算法来处理任何类型的输入,为每个输入移位位,并以尽可能快的方式在两个阵列之间应用逻辑运算 经过一点研究,我考虑将int数组转换为bool数组,

我正试图找到解决以下问题的更快方法

我有两个表示位的int数组,这里是一个8位数组的例子

int[] intArray1 = new[] {1, 1, 1, 0, 1, 1, 0, 1};
int[] intArray2 = new[] {0, 1, 0, 0, 1, 0, 0, 1};
阵列中的位数可以是8、32、64和64+

因此,我应该能够创建一个算法来处理任何类型的输入,为每个输入移位位,并以尽可能快的方式在两个阵列之间应用逻辑运算

经过一点研究,我考虑将int数组转换为bool数组,并使用bool数组创建一个位数组,因为位数组有一个构造函数,它支持bool作为位,并具有内置的位操作

bool[] boolArray = intArray.Select(s => s.Equals(1)).ToArray();
BitArray bitArray = new BitArray(boolArray);
然而,它不支持内置的位移动,它需要进行迭代,失去我试图实现的整个性能点

我可以使用int32和int64,但该解决方案不适用于大于64位的大小


善良的问候

为什么不直接使用
大整数

您可以使用此方法将
字符串
转换为
大整数

public static BigInteger BinToDec(string value)
{
    // BigInteger can be found in the System.Numerics dll
    BigInteger res = 0;

    // I'm totally skipping error handling here
    foreach(char c in value)
    {
        res <<= 1;
        res += c == '1' ? 1 : 0;
    }

    return res;
}
public static BigInteger BitArrayToBigDecimal(int[] bitIntArr) {
    // BigInteger can be found in the System.Numerics dll
    BigInteger res = 0;

    // I'm totally skipping error handling here
    foreach(int i in bitIntArr) {
        res <<= 1;
        res += i == 1 ? 1 : 0;
    }
    return res;
}
你也可以用钻头移动它们。像这样:

var foo = BinToDec("11101101");

BigInteger fooShifted = foo >> 4;

var bar = BitArrayToBigDecimal(new[] {1, 1, 1, 0, 1, 1, 0, 1});

BigInteger barShifted = bar >> 4;

如果您有任何问题,请告诉我。

BitArray相当笨重。出于一个很好的原因,这也不容易在处理器上提高效率。它的性能超过了64位,只有汇编代码才能让它做得更好,这是MSIL无法生成的。只需在谷歌上搜索“c#bitarray shift”就可以了,很可能它们看起来会和你的有很大不同。它需要处理比64更大的输入,biginteger是64bits@MrVoid
BigInteger
动态增长。从:A
biginger
“表示任意大的有符号整数。”理论上它可以无限大,但它仅受.NET对象大小(约2GB)的限制