将 64 位数组转换为 Int64 或 ulong C#

问题描述:

我有一个 int 位数组(长度始终为 64),例如:

I have an int array of bits (length always 64) like:

1110000100000110111001000001110010011000110011111100001011100100

我想把它写在一个 Int64(或 ulong?)变量中.怎么做?

and I want to write it in one Int64 (or ulong?) variable. How to do it?

我尝试创建一个 BitArray 然后获取 int,但它在 CopyTo 行上抛出 System.ArgumentException:

I tried to create a BitArray and then get int, but it throws System.ArgumentException, on CopyTo line:

private static Int64 GetIntFromBitArray(BitArray bitArray) {
    var array = new Int64[1];
    bitArray.CopyTo(array, 0);
    return array[0];
}

那是因为如文档,

指定的数组必须是兼容的类型.仅支持 bool、int 和 byte 类型的数组.

The specified array must be of a compatible type. Only bool, int, and byte types of arrays are supported.

所以你可以这样做:(未测试)

So you could do something like this: (not tested)

private static long GetIntFromBitArray(BitArray bitArray)
{
    var array = new byte[8];
    bitArray.CopyTo(array, 0);
    return BitConverter.ToInt64(array, 0);
}

查看BitArray.CopyTo的实现,将位复制到int[](然后构建long)会更快代码>从它的两半),可能看起来像这样:(也未测试)

Looking at the implementation of BitArray.CopyTo, it would be faster to copy the bits into an int[] (and then build the long from its two halves), that could look something like this: (also not tested)

private static long GetIntFromBitArray(BitArray bitArray)
{
    var array = new int[2];
    bitArray.CopyTo(array, 0);
    return (uint)array[0] + ((long)(uint)array[1] << 32);
}

转换为 uint 是为了防止符号扩展.

Casts to uint are to prevent sign-extension.