Search code examples
c#asp.netintbitbitarray

convert from BitArray to 16-bit unsigned integer in c#


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?


Solution

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