#include #include unsigned short summera(unsigned short x, unsigned short y){ if ((int)x + (int)y > 65535){ return (x + y) + 1; } return x + y; } unsigned short sum(unsigned short x, unsigned short y){ return x + y; } int main() { // Used by the random number generator. It makes sure that the random numbers // generated are different when the program is run more than once. time_t t; srand((unsigned) time(&t)); const int nbrWords = 4; //The number of 16-bit words in a package const int nbrFaults = 2; //The number of faults in each packet // Used when a bit is changed in a data word, position[i] = 1 in bit number i, 0 in all other bits unsigned short position[16]; position[0] = 1; for (int i = 1; i < 16; i++){ position[i] = position[i - 1]*2; } int numberThrown = 0; //Counts the number of packets that are regarded as correct by the receiver for (int k = 0; k < 100000; k++){ unsigned short packet[nbrWords + 1]; //The packet that will be generated. After that a number of bits //are changed and then it is seen if the checksum still is FFF //The data of the packet is given a random content for (int i = 0; i < nbrWords; i++){ packet[i] = (rand() % 0x100)*0x100 + (rand() % 0x100); } //The checksum is calculated and added to the packet unsigned short checksum = packet[0]; for (int i = 1; i < nbrWords; i++){ checksum = summera(checksum, packet[i]); } packet[nbrWords] = 0xFFFF - checksum; //nabFaults bits are changed, the result is put in the packet badPacket int nbrChanged = 0; unsigned short used[nbrWords + 1]; for (int i = 0; i <= nbrWords; i++){ used[i] = 0x0000; } unsigned short badPacket[nbrWords + 1]; for (int n = 0; n <= nbrWords; n++){ badPacket[n] = packet[n]; } while (nbrChanged < nbrFaults){ int row = rand() % (nbrWords + 1); int pos = rand() % 16; if (!(used[row]&position[pos])){ badPacket[row] = (badPacket[row]^position[pos]); used[row] = used[row] + position[pos]; nbrChanged++; } } //It is checked if badPacket will be accepted by the receiver. If so, numberFaults is increased. unsigned short test2 = badPacket[0]; for (int i = 1; i <= nbrWords; i++){ test2 = summera(test2, badPacket[i]); } if (test2 != 0xFFFF){ numberThrown++; } } printf("Number thrown: %i", numberThrown); return 0; }