简体   繁体   中英

Encode bool array as ushort

Let's assume we have an array of Boolean values, some are true some are false. I like to generate a ushort and set the bits according to the array.

A ushort consists of 2 bytes, - that makes up 16 bits.

So the first bool in the array need to set the first bit of the ushort if it's true, otherwise the bit would be 0. This needs to be repeated for each bit in the ushort .

How would I setup a method stub which takes an array of bools as input and returns the encoded ushort? (C#)

You can make use of the BitConverter class ( https://msdn.microsoft.com/en-us/library/bb384066.aspx ) in order to convert from bytes to an int, and binary operations (like in this StackOverflow question: How can I convert bits to bytes? ) to convert from bits to bytes

For Example:

//Bools to Bytes...
bool[] bools = ...
BitArray a = new BitArray(bools);
byte[] bytes = new byte[a.Length / 8];
a.CopyTo(bytes, 0);
//Bytes to ints
int newInt = BitConverter.ToInt32(bytes); //Change the "32" to however many bits are in your number, like 16 for a short

This will only work for one int, so if you have multiple int's in a single bit array, you'll need to split up the array for this approach to work.

A BitArray might be more suitable for your use case: https://msdn.microsoft.com/en-us/library/system.collections.bitarray(v=vs.110).aspx

bool[] myBools = new bool[5] { true, false, true, true, false };
BitArray myBA = new BitArray(myBools);

foreach (var value in myBA)
{
    if((bool)value == true)
    {
    }
    else
    {
    }
}

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