#include #include #include "hamming.h" //is there a one at bit position "position" of "value"? int isOneAt(int position, int value) { //position count starts at 1, not 0 return ((value >> position-1) & 1); } //returns the value of the bit at position "position" of "value" int getBitVal(int position, int value) { //position count starts at 1, not 0 return ((isOneAt(position,value)) ? 1 : 0); } //set position "position" of "value" to "bit" int setBitVal(int position, int value, int bit) { return ((bit>=1) ? (value | (1<<(position-1))) : (value & ~(1<<(position-1)))); } //formatted output of "len"-bit representation of an integer "n" int printBits(unsigned n,unsigned len) { if (len == 1) printf("%u",n); else { printBits(n>>1,len-1); printf("%u",n&1); if ((len%8) == 0) printf(" "); } } #define y(b) 32-(b) #define x(b) 32-5-(b) unsigned encode(unsigned x) { int p[5]; int i,j; int y=0; for (i=0;i<5;i++) p[i]=0; //map bits of x to bits of y, section by section, per T.1, assn #9 handout y = setBitVal(y(3),y,getBitVal(x(1),x)); for (i=5;i<=7;i++) y = setBitVal(y(i),y,getBitVal(x(i-3),x)); for (i=9;i<=15;i++) y = setBitVal(y(i),y,getBitVal(x(i-4),x)); for (i=17;i<=31;i++) y = setBitVal(y(i),y,getBitVal(x(i-5),x)); for (i=1;i<=31;i++) for (j=1;j<=5;j++) //if this i has a 1 in position j (i.e., i belongs to C_j) if (isOneAt(j,i)) //then if the plaintext x has a 1 in position i toggle parity of C_j if (isOneAt(y(i),y)) p[j-1] = 1-p[j-1]; //map parity bits onto y, per T.1, assn #9 handout for (i=0;i<=4;i++) y=setBitVal(y(pow(2,i)),y,p[i]); return y; }