Home > Mobile >  I am trying to calculate 8-bit parity in a 64-bit word in C
I am trying to calculate 8-bit parity in a 64-bit word in C

Time:03-28

I have written a small function to calculate even parity for each 8-bit block in a 64-bit word. The function is producing incorrect results.

The following is the output for Ukey = 0x666F6F6261723132

Incorrect Output:

01100110 01101111 01101111 01100010 01100001 01110010 00110001 00110010

Correct Output:

Correct Even Parity: 01100110 01101111 01101111 01100011 01100000 01110010 00110000 00110011

KEYBITSLEN is defined as 64

BYTELEN is defined as 8

void KeyParity (uint64_t *Ukey)
{
        int ParityBit;
        int i, j;
   
        ParityBit = 0;
   
        for (i = 0; i < KEYBITSLEN; i  )
        {
            for (j = 0; j < BYTELEN; j  )
            {
                if(*(Ukey i) & (0x01 << j))
                ParityBit = !ParityBit;
            }
            if (i % 8 == 7)
            {
                *(Ukey i) = ParityBit;
                ParityBit = 0;
            }
        }
}

CodePudding user response:

This line looks suspicious:

if(*(Ukey i) & (0x01 << j))

So does this line:

*(Ukey i) = ParityBit;

When i != 0, UKey i is pointing to an entirely different 64-bit value from what Ukey points to in undefined memory space. Unless Ukey is pointing to an element of an array, this is undefined behavior.

Maybe this is closer to what you really want:

uint8_t KeyParity(uint64_t UKey)
{
    uint8_t result = 0;
    bool odd = false;

    for (unsigned int i = 0; i < 64; i  )
    {
        if ((1ULL << i) & UKey)
        {
            odd = !odd;
        }

        if ((i % 8) == 7)
        {
            uint8_t parity = odd ? 1 : 0;
            parity = parity << (i/8);
            result = result | parity;
            odd = false;
        }
    }

    return result;
}

CodePudding user response:

In the title you ask for "8-bit parity of a 64-bit word", but then in the body you say "even parity of each 8-bit block in a 64-bit word". These are two totally different things. Worse, these are both 8-bit values, but your "desired output" is 64 bits for a 64 bit input (which makes no sense).

You could try either:

// compute the 8-bit parity of a 64 bit number
uint8_t EightBitParity(uint64_t val) {
    val ^= val >> 32;
    val ^= val >> 16;
    val ^= val >> 8;
    return val & 0xff;
}

// compute parity of each 8-bit byte of a 64-bit number;
uint8_t ParityOfBytes(uint64_t val) {
    val ^= val >> 4;
    val ^= val >> 2;
    val ^= val >> 1;
    val &= 0x0101010101010101;
    val |= val >> 28;
    val |= val >> 14;
    val |= val >> 7;
    return val & 0xff;
}  
    
  •  Tags:  
  • c
  • Related