Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Expands 16 bits to 24 bits by generating a parity byte.
- This parity byte allows recovering from any single-bit errors during transmission.
- Both the data and parity bytes would be transmitted.
- This could be used, in addition to CRC or similar, as a first line of defense against transmission errors.
- Small single-bit errors could potentially be recovered, rather than requiring the CRC check to fail and the message needing to be resent.
- This scheme is derived from Hamming Codes, but differs mostly in that bits are organized into a "sane" ordering (with data bits left in their original order).
- */
- #if 0
- /** Generate Parity Byte via XOR */
- byte H16_PByteForByte(byte v)
- {
- byte p0, p1, p2, p3;
- byte p4, p5, p6, p7;
- byte p;
- p0=(v>>0)^(v>>1)^(v>>3)^(v>>4)^(v>>6);
- p1=(v>>0)^(v>>2)^(v>>3)^(v>>5)^(v>>6);
- p2=(v>>1)^(v>>2)^(v>>3)^(v>>7);
- p3=(v>>4)^(v>>5)^(v>>6)^(v>>7);
- p0&=1; p1&=1; p2&=1; p3&=1;
- p=p0|(p1<<1)|(p2<<2)|(p3<<3);
- return(p);
- }
- #endif
- #if 1
- /** Generate Parity Byte via lookup table */
- byte H16_PByteForByte(byte v)
- {
- static const byte pbtab[64]={
- 0x30,0x65,0x56,0x03,0x47,0x12,0x21,0x74,
- 0xA9,0xFC,0xCF,0x9A,0xDE,0x8B,0xB8,0xED,
- 0x9A,0xCF,0xFC,0xA9,0xED,0xB8,0x8B,0xDE,
- 0x03,0x56,0x65,0x30,0x74,0x21,0x12,0x47,
- 0x8B,0xDE,0xED,0xB8,0xFC,0xA9,0x9A,0xCF,
- 0x12,0x47,0x74,0x21,0x65,0x30,0x03,0x56,
- 0x21,0x74,0x47,0x12,0x56,0x03,0x30,0x65,
- 0xB8,0xED,0xDE,0x8B,0xCF,0x9A,0xA9,0xFC
- };
- byte p;
- p=(v&0x80)?pbtab[(0xFF-v)>>1]:pbtab[v>>1];
- p=(v&0x01)?(p>>4):(p&15);
- return(p);
- }
- #endif
- /** Get parity byte for a pair of bytes. */
- byte H16_PByteForPair(u16 v)
- {
- byte p0, p1, p;
- p0=H16_PByteForByte((v )&255);
- p1=H16_PByteForByte((v>>8)&255);
- p=p0|(p1<<4);
- return(p);
- }
- /* Recover a byte given parity bits. */
- u16 H16_RecoverByte(byte vi, byte pi, byte pj)
- {
- static const byte xmtab[16]={
- 0x00, 0xFF, 0xFF, 0x01, 0xFF, 0x02, 0x04, 0x08,
- 0xFF, 0x10, 0x20, 0x40, 0x80, 0xFF, 0xFF, 0xFF
- };
- byte xm;
- xm=xmtab[(pi^pj)&15];
- if(xm==0xFF) /* Invalid combination of parity bits. */
- { xm=0x00; }
- return(vi^xm);
- }
- /** Recover a pair of bytes given the parity byte. */
- u16 H16_RecoverPair(u16 vi, byte pi)
- {
- int v0, v1, v;
- byte pj;
- pj=H16_PByteForPair(vi);
- if(pi==pj)
- {
- /* If parity bytes agree, assume there is no error. */
- return(vi);
- }
- v0=H16_RecoverByte(vi>>0, pi>>0, pj>>0);
- v1=H16_RecoverByte(vi>>8, pi>>4, pj>>4);
- v=v0|(v1<<8);
- return(v);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement