How can I convert BitArray to single int?

后端 未结 4 883
借酒劲吻你
借酒劲吻你 2020-11-27 05:07

How can I convert BitArray to a single int?

相关标签:
4条回答
  • 2020-11-27 05:26
    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;
    }
    
    0 讨论(0)
  • 2020-11-27 05:26

    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;
    }
    
    0 讨论(0)
  • 2020-11-27 05:42

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

    0 讨论(0)
  • 2020-11-27 05:46
    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];
    
    }
    
    0 讨论(0)
提交回复
热议问题