47

How can I convert BitArray to a single int?

1
  • BitArray to int Array or literally a BitArray to a single integer? Mar 12, 2011 at 14:49

4 Answers 4

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

}
3
  • 1
    Wow... I didn't think this would work to put all the bits into one integer value - but it does!
    – codekaizen
    Nov 19, 2011 at 11:27
  • 4
    Refer this: codereview.stackexchange.com/questions/3796/… Need to check the length of bitArray
    – coder_bro
    Aug 2, 2012 at 6:41
  • 5
    Nice trick, however it could have issues related to byte order (endianess) on various platforms. It would be better to use byte array as destination for bit array copy and use BitConverter.ToInt32(array, 0) method afterwards. Feb 8, 2019 at 12:09
10

This version:

  • works for up to 64 bits
  • doesn't rely on knowledge of BitArray implementation details
  • doesn't needlessly allocate memory
  • doesn't throw any exceptions (feel free to add a check if you expect more bits)
  • should be more than reasonably performant

Implementation:

public static ulong BitArrayToU64(BitArray ba)
{
    var len = Math.Min(64, ba.Count);
    ulong n = 0;
    for (int i = 0; i < len; i++) {
        if (ba.Get(i))
            n |= 1UL << i;
    }
    return n;
}
1
  • 2
    Can you explain how this is better than the accepted solution from 7 years ago? Is it faster, more accurate, better at error handling, using less memory?
    – nvoigt
    Jul 20, 2018 at 9:12
9
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;
}
5
  • Can you explain why the OP should use this over the other solution? Sep 27, 2012 at 4:47
  • 1
    @AustinHenley I wrote this solution for debug purposes. I can step through my code to see how the number is being converted. I'm not sure if you can do that with the first solution. Aug 1, 2013 at 18:34
  • 1
    It's also interesting to know that the first solution is not available on WinRT (probably because of the way ARM processors save the numbers)
    – tec-goblin
    Sep 17, 2013 at 10:19
  • 1
    I have to use this because its not available on ARM. Aug 23, 2014 at 21:32
  • 5
    The .NET Core stack may not have BitArray.CopyTo. That being said, why not 1 << i rather than Convert.ToInt16(Math.Pow(2, i))? Feb 11, 2017 at 19:39
1

Reffering to this post (#43935747). A value X is short tpe whic I set two bits (6 and 10) like below: short X=1;

        var result = X;
        var bitsToSet = new [ ] { 5,9 };
        foreach ( var bitToSet in bitsToSet )
            {
            result+=( short ) Math.Pow ( 2,bitToSet );
            }
        string binary = Convert.ToString ( result,2 );

Now I would like to read the specific all bits from Value X and put it in to an array or a bit type like bool Val1= bit1, bool Val2=bit2....

I am a newbie and I think it is pretty simple for you guyes..

1
  • OK but you should make it |= and (short)(1 << bitToSet) to make it more obvious at a glance. It's not like this code is incomprehensible, but it relies on the combination of some "carefully chosen coincidences" instead of just obviously doing the right thing.
    – harold
    May 12, 2017 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.