How can I convert BitArray to single int?

2019-01-05 02:54发布

How can I convert BitArray to a single int? The fastest way pls...

4条回答
Summer. ? 凉城
2楼-- · 2019-01-05 03:21

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;
}
查看更多
Juvenile、少年°
3楼-- · 2019-01-05 03:22
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];

}
查看更多
欢心
4楼-- · 2019-01-05 03:36
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楼-- · 2019-01-05 03:36

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

查看更多
登录 后发表回答