简体   繁体   中英

Convert ushort array to bit array

I have a ushort array:

ushort[] testArray = new ushort[]{1, 2, 3, 4, 5};

How I can convert it to a bit Array. In the above example, a length of 5 * 16 bit array? Thanks in advance!

Pretty simple google search gives this BitArray Class

Example

using System.Collections;

int[]  myInts  = new int[5] { 6, 7, 8, 9, 10 };
BitArray myBA5 = new BitArray( myInts );

Update:

So I was interested in the problem and decided to complete a working solution. This is what I'd do to handle shorts. One thing though is I'm assuming the bits will still translate given that you aren't trying to re-interperate back (??) and just want to loop through the raw bits?

var shorts = new ushort[] { 5, 1 };
var numberOfInts = (int)Math.Ceiling((decimal)shorts.Length / 2);
var theInts = new int[numberOfInts];

var shortsPos = 0;
for (int i = 0; i < numberOfInts; i++)
{   
    theInts[i] = shorts[shortsPos + 1];
    theInts[i] = theInts[i] | ((int)shorts[shortsPos] << 16);
    shortsPos =+ 2;
    //theInts[i].Dump();
}

var bitArr = new BitArray(theInts);
foreach (var bit in bitArr)
{
    //bit.Dump();
}

I mocked this up in LinqPad hence the .Dump() statements so do you're own thing for testing. You may have to switch around the order and maybe shift the second in each pair...I'll leave that part for you to work out. Also if you just have a single value in your source ushort[] you'll get an error so work out the maths to sort that out too..

The result of the above is:

True
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
True
False
True
False
False
False
False
False
False
False
False
False
False
False
False
False
            int[] testArray = new int[] { 1, 2, 3, 4, 5 };
            Dictionary<int, int[]> convertData = new Dictionary<int, int[]>();

            foreach (int x in testArray)
            {
                System.Collections.BitArray b = new System.Collections.BitArray(Convert.ToByte(x));
                convertData[x] = b.Cast<bool>().Select(bit => bit ? 1 : 0).ToArray();
            }

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