In c you have the possibility to add up your bools and then mod the result with 2, but in the stricter typed language c# you have to add a lot of typecasts to do the same. I hope there is some more esthetical way of doing this?
c sourcecode:
int array_out[12];
...
array_out[11] = (array_out[0] + array_out[1] + array_out[2] + array_out[3] + array_out[4] + array_out[5] + array_out[6] + array_out[7] + array_out[8] + array_out[9] + array_out[10]) % 2;
c# equivalent:
bool[] array_out= new bool[12];
...
array_out[11] = (((array_out[0] ? 1 : 0) + (array_out[1] ? 1 : 0) + (array_out[2] ? 1 : 0) + (array_out[3] ? 1 : 0) + (array_out[4] ? 1 : 0) + (array_out[5] ? 1 : 0) + (array_out[6] ? 1 : 0) + (array_out[7] ? 1 : 0) + (array_out[8] ? 1 : 0) + (array_out[9] ? 1 : 0) + (array_out[10] ? 1 : 0)) % 2) == 1;
Loading
AlanPosted Jun 12, 2007, 7:12 PM
In C#, there is no built-in conversion between bool and int, even an explicit one using a cast, though this will work subject to the overhead of a function call:
int i = System.Convert.ToInt32(true); // i == 1
int j = System.Convert.ToInt32(false); // j == 0
However, I think the most elegant way of doing this (as in C itself) is to use a loop:
bool[] array_out= new bool[12];
.....
int temp = 0;
for(int i = 0; i < 11; i++)
{
temp += array_out[i] ? 1 : 0;
}
temp %= 2;
array_out[11] = (temp == 1);