Reputation: 29
Good morning !
For a wireless application i need to implement various CRC-Caluclations. According to the Specification, the CRC-Calculation should be implemented as a Shift Register. See EPC Spec
There is a excellent guide called "A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS" by Ross N. Williams, which includes a universal C implementation i would like to use. (Link including the SourceCode)
The problem is that the included function only takes complete bytes as input. My messages can have various lengths.
Here is the code for adding a byte:
void cm_nxt(p_cm,ch)
p_cm_t p_cm;
int ch;
{
int i;
ulong uch = (ulong)ch;
ulong topbit = BITMASK(p_cm->cm_width - 1);
if (p_cm->cm_refin) uch = reflect(uch, 8);
p_cm->cm_reg ^= (uch << (p_cm->cm_width - 8));
for (i = 0; i <8; i++) {
if (p_cm->cm_reg & topbit)
p_cm->cm_reg = (p_cm->cm_reg << 1) ^ p_cm->cm_poly;
else
p_cm->cm_reg <<= 1;
p_cm->cm_reg &= widmask(p_cm);
}
}
Now I would like to implement a function just to add one Bit to the calculation. I tried the following code:
void cm_nxt_bit(p_cm, ch)
p_cm_t p_cm;
int ch;
{
ulong uch = (ulong)ch;
ulong topbit = BITMASK(p_cm->cm_width - 1);
if (p_cm->cm_refin) uch = reflect(uch, 8);
p_cm->cm_reg ^= (uch << (p_cm->cm_width - 8));
if (p_cm->cm_reg & topbit)
p_cm->cm_reg = (p_cm->cm_reg << 1) ^ p_cm->cm_poly;
else
p_cm->cm_reg <<= 1;
p_cm->cm_reg &= widmask(p_cm);
}
Unfortunately it doesnt work as intended. Can you help me to implement such a function ?
Upvotes: 1
Views: 285
Reputation: 112607
You need to put the one bit at the top of the register, just like the other code put the one byte at the top of the register. Assuming that ch
must be either 0
or 1
, so that the bit you are adding is the bottom bit of ch
, you then need to shift uch
up by cm_width-1
, not cm_width-8
before exclusive-oring into the register.
Also get rid of the use of reflect
. The reflection of one bit is that same one bit.
Also you can look my crcany code, which generates CRC code in C for any CRC definition, including a routine that will compute the CRC of the last 1 to 7 bits of a stream if it is not a multiple of eight bits in length.
Upvotes: 2