Search code examples
c#64-bitbit-manipulationtypeconverterbitarray

Convert 64 bits array into Int64 or ulong C#


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

Solution

  • 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.