Convert 64 bits array into Int64 or ulong C#
Asked Answered
N

1

7

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];
}
Neurotic answered 4/4, 2015 at 11:33 Comment(0)
A
9

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.

Annamariaannamarie answered 4/4, 2015 at 12:4 Comment(1)
Great! You make my day! Solved.Neurotic

© 2022 - 2024 — McMap. All rights reserved.