-1

The question is about code in figure 14-6 in here.

The mask is calculated as:

mask = -(crc & 1)

Why do we & crc with 1 and then make result negative? The Figure 14-5 does not have this mask variable, why?

Edit:

So since this point is clear, why do we have this line also:

crc = crc ^ byte;

This line is not present in Figure 14-5.

Can this program be used if the generator polynomial length is not multiple of 8 bits?

quantum231
  • 2,420
  • 3
  • 31
  • 53

2 Answers2

1

What that does is to check the least significant bit of crc and then negating it. The effect is that if the bit is zero the mask will be zero (that is all zeroes) and if the bit is one the mask will be -1 (that is all ones). This is used to conditionally xor with 0xEDB88320.

The other solution instead uses if to make that condition.

The second trick they're using in the second solution is to do the xor for the bit check in one operation for all eight bits. In the first example they use (int)(crc^byte) < 0 (which means a check for the XOR of the most significant bit or the sign bit), they then shift both crc and byte one bit to the left and do the same on next bit. In the second example they do the XOR eight bits at a time and then checks each bit of the result.

To see what happens, consider if we change the first example to:

for(j=0; j<=7; j++) {
    crc = crc ^ mask_sign_bit(byte); 
    if( (int)crc < 0 )
        crc = (crc << 1) ^ 0x04C11DB7;
    else
        crc = crc << 1;
    byte = byte << 1;
}

where mask_sign_bit masks out every bit except the sign bit, the sign of crc ^ byte becomes the same as crc ^ mask_sign_bit(byte) so the consequence of the if statement becomes the same. Then when shifting crc to the left one step the bit modified by crc = crc ^ mask_sign_bit(byte) will be lost.

skyking
  • 13,817
  • 1
  • 35
  • 57
0

This operation turns the least significant bit into a mask.

For example, for an 8-bit value (for simplicity) we have:

00000000 -> 00000000
00000001 -> 11111111

Using unary minus complicates the circuitry of the CRC function massively, which otherwise requires no addition operations. It can be implemented as function of addition, as follows

-x = ~x + 1

Some architectures might support a bit-vector "broadcast" operation, to send the least significant bits to all others bits, which will give huge performance gain.