How to add even parity bit on 7-bit binary number

后端 未结 3 983
陌清茗
陌清茗 2021-01-25 11:29

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

3条回答
  •  青春惊慌失措
    2021-01-25 11:57

    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.

提交回复
热议问题