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

后端 未结 3 1015
陌清茗
陌清茗 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: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);
    }
    

提交回复
热议问题