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

*爱你&永不变心* 提交于 2019-12-02 08:05:57

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.

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);
}

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!