#include #include #include #define INT_SIZE 2 void decodeH(unsigned short in[], unsigned short out[],int N){ unsigned int j=0, /* The C index of the next code word */ i, /* Index into the block of code words */ c[N+1], /* The table of control words */ p=0, /* The C index of first free control word, j=2^p-1 */ q, /* Index into the table of computed control words */ bit, /* Bit position in a code word of a possible error */ marks=0 /* Bit positions to indicate presense of errors */ ; for (i=0; p<=N; i++) /* Find control words 0..p */ if (i == j) { c[p] = in[i]; p++; j += j+1; } else for (bit=1,q=0;q>=1,bit<<=1) if (marks & 1) { /* On error: find its index position */ i=0; for (q=N; q; q--) if (c[q-1] & bit) i += i+1; else i += i; in[i-1] ^= bit; /* Correct the bit in the received word */ } } /* Move data from in to out */ for (j=p=i=0; p<=N; i++) if (i==j) {j += j+1; p++;} else out[i-p] = in[i]; } void readAndDecode(int codeblock, int datablock, int N){ short buffer1[datablock], // for decoded data to be written buffer2[datablock], // a lookahead block is needed *prev,*last, *tmp, // pointers to buffers inbuffer[codeblock], // encoded data to be read wanted, // count of bytes to be read count; // count of bytes actually read char *inptr; // pointer to next free in inbuffer count = 0; last = 0; prev = 0; do { // read a block of data from stdin and decode it inptr = (char*) inbuffer; wanted = codeblock*INT_SIZE; while (wanted && 0 < (count = read(STDIN_FILENO, inptr, wanted))) { wanted -= count; inptr += count; } if (count == 0) { // eof has occurred // write(STDOUT_FILENO,"|2|",3); if (last[datablock-1] >= datablock*INT_SIZE) { // the unwritten data are all in the prev-block write(STDOUT_FILENO,prev,2*datablock*INT_SIZE-last[datablock-1]); break; } // write(STDOUT_FILENO,"|3|",3); if (prev) write(STDOUT_FILENO,prev,datablock*INT_SIZE); // write(STDOUT_FILENO,"|4|",3); if (last) write(STDOUT_FILENO,last,datablock*INT_SIZE-last[datablock-1]); break; } // a new block of encoded data has been read // find a buffer for the decoded data // write the prev-block to stdout, if present if (prev) { // write(STDOUT_FILENO,"|1|",3); write(STDOUT_FILENO,prev,datablock*INT_SIZE); tmp = prev; prev = last; last = tmp; } else if (last) { prev = last; last = buffer2; } else last = buffer1; if (count > 0) { decodeH(inbuffer,last,N); } else { perror("Decoder"); exit(1); } } while (1); } int main(int argc, char *argv[]){ int N, // The number of auxiliary bit in a Hamming code. codeblock, // The length of an encoded block datablock; // The length of a block of data N = 4; codeblock = (1<