I am continuing from my previous question. I am making a c# program where the user enters a 7-bit binary number and the computer prints out the number with an even parity bit to
Using a BitArray
does not buy you much here, if anything it makes your code harder to understand. Your problem can be solved with basic bit manipulation with the &
and |
and <<
operators.
For example to find out if a certain bit is set in a number you can & the number with the corresponding power of 2. That leads to:
int bitsSet = 0;
for(int i=0;i<7;i++)
if ((number & (1 << i)) > 0)
bitsSet++;
Now the only thing remain is determining if bitsSet
is even or odd and then setting the remaining bit if necessary.