How can I convert BitArray to single int?

大憨熊 提交于 2019-12-17 04:29:42

问题


How can I convert BitArray to a single int?


回答1:


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

}



回答2:


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



回答3:


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



回答4:


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



来源:https://stackoverflow.com/questions/5283180/how-can-i-convert-bitarray-to-single-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!