Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert BitArray to single int?

How can I convert BitArray to a single int?

like image 921
Vlad Omelyanchuk Avatar asked Mar 12 '11 14:03

Vlad Omelyanchuk


2 Answers

private int getIntFromBitArray(BitArray bitArray)
{

    if (bitArray.Length > 32)
        throw new ArgumentException("Argument length shall be at most 32 bits.");

    int[] array = new int[1];
    bitArray.CopyTo(array, 0);
    return array[0];

}
like image 191
Luca Fagioli Avatar answered Nov 10 '22 00:11

Luca Fagioli


private int getIntFromBitArray(BitArray bitArray)
{
    int value = 0;

    for (int i = 0; i < bitArray.Count; i++)
    {
        if (bitArray[i])
            value += Convert.ToInt16(Math.Pow(2, i));
    }

    return value;
}
like image 10
K4KNOWLEDGE Avatar answered Nov 10 '22 01:11

K4KNOWLEDGE