0

I'm not sure if there is better method for converting several boolean variables into a single integer.

This way is working but maybe there is a better way to do it:

bool bit1 = true;
bool bit2 = false;
bool bit3 = true;
bool bit4 = true;
bool bit5 = false;
bool bit6 = false;
bool bit7 = false;
bool bit8 = true;

int value = Convert.ToInt16(bit8) << 7 | Convert.ToInt16(bit7) << 6 | Convert.ToInt16(bit6) << 5 | Convert.ToInt16(bit5) << 4 | Convert.ToInt16(bit4) << 3 | Convert.ToInt16(bit3) << 2 | Convert.ToInt16(bit2) << 1 | Convert.ToInt16(bit1) << 0;

Thanks

Pabinator
  • 1,601
  • 1
  • 21
  • 25
  • You just basically made a `BitArray`: https://msdn.microsoft.com/en-us/library/system.collections.bitarray%28v=vs.110%29.aspx – Dennis_E Jun 16 '15 at 20:47
  • You just did it in the most efficient way possible.... a single line. What more would you want? – maraaaaaaaa Jun 16 '15 at 20:57
  • Hi @David the question that you refer as duplicate is exactly the opposite of what I was looking for but also it helped me to convert an `int` into several `booleans`. Thanks for the link. – Pabinator Jun 17 '15 at 16:32
  • @Pabinator: Admittedly, I didn't realize Stack Overflow was going to take *only* my word for it and close the question with only a single vote. It was more of a suggestion than a proven fact, and I was expecting the system to require more votes :-/ – David Jun 17 '15 at 16:34

1 Answers1

2

You can create a for that will create the number. Doing this you don't have to worry about the Length of the number and the code will be more cleaner.

bool[] number = new[] { bit1, bit2, bit3, bit4, bit5, bit6, bit7, bit8 };
int value = 0;
for (int i = 0; i < number.Length; i++)
{
    value |= Convert.ToInt16(number[i]) << i;
}
adricadar
  • 9,971
  • 5
  • 33
  • 46