转换64位数组的Int64或ULONG C#数组、ULONG

2023-09-08 01:13:00 作者:伱给德伤,俄永远都记得。

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

 1110000100000110111001000001110010011000110011111100001011100100 

和我想在一个的Int64 (或ULONG?)可变写。怎么办呢?

我试图创建一个 BitArray ,然后让 INT ,但它抛出系统.ArgumentException ,CopyTo从上线:

 私有静态的Int64 GetIntFromBitArray(BitArray bitArray){
    变种数组=新的Int64 [1];
    bitArray.CopyTo(阵列,0);
    返回数组[0];
}
 

解决方案 C语言数组指针内存释放

这是因为在的文档,

  

指定数组必须是兼容类型。只有BOOL,INT和字节数组类型的支持。

所以,你可以做这样的事情:(未测试)

 私有静态长GetIntFromBitArray(BitArray bitArray)
{
    VAR阵列=新的字节[8]。
    bitArray.CopyTo(阵列,0);
    返回BitConverter.ToInt64(阵列,0);
}
 

看着 BitArray.CopyTo 的实施,这将是更快位复制到一个 INT [] (然后生成从两半),这可能会是这个样子:(也未测试)

 私有静态长GetIntFromBitArray(BitArray bitArray)
{
    变种数组=新INT [2];
    bitArray.CopyTo(阵列,0);
    返回(UINT)阵列[0] +((长)(UINT)阵列[1];< 32);
}
 

强制转换为 UINT 是prevent符号扩展。

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

1110000100000110111001000001110010011000110011111100001011100100

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

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];
}

解决方案

That is because as mentioned in the documentation,

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);
}

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);
}

Casts to uint are to prevent sign-extension.

 
精彩推荐
图片推荐