3
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?

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

res |= (1 << i); can not convert integer(i) to UInt16 (res) ??
@user2922938 Oops, I forgot to add a cast. This should work after the edit.
plz i am beginner in c# can you explain more,what is (cast)?
@user2922938 I added (uint16) in front of (1 << i) to tell C# that the expression needs to be converted to uint16 before using it in an OR.
0

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

Comments

0

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

Comments

-1

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

Convert bit array to uint or similar packed value

1 Comment

That example uses COPYTO and he cannot use that as mentioned in the question

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.