简体   繁体   中英

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

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

有 bitArray,我想在 c# 中将此数组中的 16 位转换为无符号整数,我不能使用 copyto 进行转换,还有其他方法可以从16-bit转换为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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM