I have a class that is parsing an object to be sent to a another hardware device. The class contains a bunch of features that are either enabled or disabled (bools). However, we only write words to data to the piece of hardware (essentially a uint, or 16-bit integer).
Therefore, I need to translate
Feature1 (bool, true)
Feature2 (bool, false)
Feature3 (bool, false)
Feature4 (bool, false)
...
Feature16 (bool, false)
and parse it into a single word:
000000000001
The device sees a word as little-endian, fyi.
I was trying to bitwise-or against a uint, but the fact that the flags are bools makes this messy so I was wondering if anyone else had any slick suggestions 😉
EDIT: No sooner than I post this, I relaxed and thought of this solution…
private static ushort BooleanToUint(List<bool> bools)
{
ushort word = 0;
for(int i = 0; i < bools.Count; i++)
{
if(bools[i])
{
int twoToPower = (1 << i);
word = (ushort) (word + twoToPower);
}
}
return word;
}
If you have your boolean values in an array you can just use to index to set the corresponding bit (if set):