문제

BitArray bits=new BitArray(16); // size 16-bit

There is bitArray and I want to convert 16-bit from this array to unsigned integer in c# , I can not use copyto for convert, is there other method for convert from 16-bit to UInt16?

도움이 되었습니까?

해결책

You can do it like this:

UInt16 res = 0;
for (int i = 0 ; i < 16 ; i++) {
    if (bits[i]) {
        res |= (UInt16)(1 << i);
    }
}

This algorithm checks the 16 least significant bits one by one, and uses the bitwise OR operation to set the corresponding bit of the result.

다른 팁

You can loop through it and compose the value itself.

var bits = new BitArray(16);
bits[1] = true;
var value = 0;

for (int i = 0; i < bits.Length; i++)
{
    if (lBits[i])
    {
        value |= (1 << i);
    }
}

This should do the work

    private uint BitArrayToUnSignedInt(BitArray bitArray)
    {
        ushort res = 0;
        for(int i= bitArray.Length-1; i != 0;i--)
        {
            if (bitArray[i])
            {
                res = (ushort)(res + (ushort) Math.Pow(2, bitArray.Length- i -1));
            }
        }
        return res;
    }

You can check this another anwser already in stackoverflow of that question:

Convert bit array to uint or similar packed value

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top