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

后端 未结 3 958
陌清茗
陌清茗 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:45

    Might be more fun to duplicate the circuit they use to do this..

    bool odd = false;
    
    for(int i=6;i>=0;i--)
      odd ^= (number & (1 << i)) > 0;
    

    Then if you want even parity set bit 7 to odd, odd parity to not odd.

    or

    bool even = true;
    
    for(int i=6;i>=0;i--)
      even ^= (number & (1 << i)) > 0;
    

    The circuit is dual function returns 0 and 1 or 1 and 0, does more than 1 bit at a time as well, but this is a bit light for TPL....

    PS you might want to check the input for < 128 otherwise things are going to go well wrong.

    ooh didn't notice the homework tag, don't use this unless you can explain it.

    0 讨论(0)
  • 2021-01-25 11:51

    Almost the same process, only much faster on a larger number of bits. Using only the arithmetic operators (SHR && XOR), without loops:

    public static bool is_parity(int data)
    {
        //data ^= data >> 32; // if arg >= 64-bit (notice argument length)
        //data ^= data >> 16; // if arg >= 32-bit 
        //data ^= data >> 8;  // if arg >= 16-bit
        data ^= data >> 4;
        data ^= data >> 2;
        data ^= data >> 1;
        return (data & 1) !=0;
    }
    
    public static byte fix_parity(byte data)
    {
        if (is_parity(data)) return data;
        return (byte)(data ^ 128);
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题