Cycle II [CCN Hardware]

CCN Lab Manual

CCN Programming using C/C++

1. Simulate bit/character stuffing and de-stuffing in HDLCFraming involves identifying the beginning and end of a block of information within adigital stream. Framing assumes that there is enough synchronization at the physical layerto at least identify an individual bit or byte.In asynchronous data transmission , sincetransmissions do not occur at regular intervals , the receiver resynchronizes at the start ofeach eight bit character by the use of a start bit that precedes and a stop bit that ends eachcharacter .In synchronous data transmission bits are transmitted at regular intervals and the receiverhas the circuitry that recovers and tracks the frequency and bit transitions of the receiveddataFraming may involve delineating the boundaries between frames that are of fixed lengthor it may involve delineating between frames that are of variable length.Variable length frames need more information to delineate . The methods availableinclude : Special characters to identify beginning and end of frame Special bit patterns-flags to identify the beginning and end of frames andcharacter countsBit Stuffing:Flag based synchronization was developed to transfer an arbitrary number of bits within a frame.The figure below shows the structure of an HDLC frame . The beginning and end of an HDLCframe is indicated by the presence of an eight bit flag. The flag in HDLC consists of the byte01111110 that is HEX 7E . Bit stuffing prevents the occurrence of the flag inside the frame. Thetransmitter examines the contents of the frame and inserts an extra 0 after each instance of fiveconsecutive 1s. The transmitter then attaches the flag at the beginning and end of the resulting bitstuffed frame. The receiver looks for five consecutive 1s in the received sequence. Five 1sfollowed by a 0 indicate that the 0 is a stuffing bit and so the bit is removed. Five consecutive 1sfollowed by 10 indicate a flag. Five 1 s followed by 11 indicate an errorThe example below show bit stuffing in HDLC

3/27

Dept of ECE

CCN Lab Manual

HDLC FrameThe high level data link control protocol is a bit oriented protocol which uses bit stuffing for datatransparency. HDLC frame is as shown.

The Control field is used for sequence numbers and acknowledgements and other purposes. TheData field may contain arbitrary information. The Checksum field is a minor variation of the CRCcode using CRC-CCITT as the generator. Frames are delimited by 0111 1110 and this sequence isnot allowed in the data field.Algorithm for Bit Stuffing1. Input data sequence2. Add start of frame to output sequence3. For every bit in inputa. Append bit to output sequenceb. Is bit a 1?Yes:Increment countIf count is 5, append 0 to output sequence and reset count4/27

Dept of ECE

CCN Lab Manual

No:Set count to 04. Add stop of frame bits to output sequence/* Program to simulate bit stuffing where the flag byte is 01111110 */# include <stdio.h># include <conio.h>void main(){/* Array is already initialised to 01111110 which is the flag byte. Hence a counter 'i'/* has to point to the eight location in the same array */char ch, array[50]={"01111110"},recd_array[50];int counter=0,i=8,j,k;clrscr();/* Only the data portion of the frame is inputted */printf("Enter the original data stream for bit stuffing : \n");while((ch=getche())!='\r'){if (ch=='1')++counter;elsecounter=0;array[i++]=ch;if (counter==5) /* If 5 ones are encountered append a zero */{array[i++]='0';counter=0;}}strcat(array,"01111110"); /* Appending the flag byte at the end of the stream *//* i now has the value of the flag byte length + data stream length */printf("\nThe stuffed data stream is : \n");for (j=0;j<i+8;++j)printf("%c",array[j]);/* Destuffing */counter=0;printf("\nThe destuffed data stream is : \n");for (j=8,k=0;j<i+8;++j){if (array[j]=='1')++counter;elsecounter=0;recd_array[k++]=array[j];if (counter==6) /* End if six ones are encountered */break;else if (counter==5 && array[j+1]=='0') /* If five ones appear, delete thefollowing zero */{++j;counter=0;5/27

Byte stuffing:Character based frame synchronization methods are used when the information in a frameconsists of an integer number of characters. For example, asynchronous transmission systems areused extensively to transmit sequences of printable characters using 8 bit ASCII code . Todelineate a frame of characters, special eight bit codes that do not correspond to printablecharacters are used as control characters. In ASCII code all characters with hexadecimal valuesless than 20 correspond to non printable characters.In particular STX (start of text ) control character has hex value 02 and indicates the beginning ofa frame and an ETX ( end of text ) character has HEX value 03 and denotes the end of a frame .This method works if the frame contains only printable characters. If a frame carries computerdata, then it is possible that an ETX character will appear inside the frame and cause the receiverto prematurely truncate the frame.This method is not transparent because the frame cannot carryall possible bit sequencesThe use of byte stuffing enables transparent operation. Byte stuffing operates as follows . Aspecial DLE ( data link escape) control with hex value 10 is introduced. The two charactersequence DLESTX is used to indicate the beginning of a frame and DLE ETX denotes the end ofa frame. The receiver looks for these character pairs to identify the beginning and end offrames.In order to deal with the occurrence of DLE STX or DLE ETX in the data contained inthe frame, an extra DLE is inserted or stuffed before the occurrence of a DLE inside the frame.Consequently every legitimate DLE in the data is replaced by two DLEs. The only incidence ofan individual DLE occurs when DLE precedes the STX or the ETX that identify the beginningand end of the frame

CCN Lab Manual

2. To Simulate the Shortest Path Algorithm

In order to transfer packets from a source host to the destination host , the network layermust determine the path or route that the packets are to follow. This is the job of thenetwork layer routing protocol.At the heart of any routing protocol is the routingalgorithm that determines the path for a packet from source router to destination router.Given a set of routers, with links connecting the routers, a routing algorithm finds a goodpath from source router to destination router, according to some cost criterion. These canbe1. Hop count : 1/ capacity: The cost is inversely proportional to the link capacity .One assigns higher costs to lower capacity links . The objective is to send a packetthrough a path through a path with the highest capacity. If each link has equalcapacity , then the shortest path is the path with the minimum number of hops2. Transmission speed: The speed at which the various links operate is an importantpart of a routes efficiency. Faster links obviously take precedence over slowones.3. Congestion : Network congestion caused by the current traffic pattern isconsidered when evaluating a route and links that are overly congested arebypassed4. Route cost : The route cost is a metric assigned by the network administrator usedto rate the relative usability of various routes . The cost can refer to the literalfinancial expense incurred by the link or any other pertinent factor.5. Packet delay: The cost is proportional to an average packet delay which includesqueuing delay in the switch buffer ad propagation delay in the link. The shortestpath represents the fastest path to reach the destinationDijkstras algorithm:Dijkstras algorithm progressively identifies the closest nodes from the source node inorder of increasing path cost. The algorithm is iterative. . The Dijkstras algorithmcalculates the shortest path between two points on a network using a graph made upof nodes and edges The algorithm divides the nodes into two sets : tentative andpermanent . It chooses nodes, makes them tentative, examines them and if they passthe criteria makes them permanent.The algorithm has the following steps1. Start with the local node (router): the root of the tree2. Assign a cost of 0 to this node and make it the first permanent node3. Examine each neighbour of the node that was the last permanent node4. Assign a cumulative cost to each node and make it tentative5. Among the list of tentative nodes(i)Find the node with the smallest cumulative cost and make itpermanent(ii)If a node can be reached from more than one directionSelect the direction with the shortest cumulative cost6.

Repeat steps 3 to 5 until every node becomes permanent

9/27

Dept of ECE

CCN Lab Manual

Algorithm1. Input graph data2. Make all nodes TENTATIVE.2. Input source, destination3. Make source, the working node4. Make the working node PERMANENT.5. Check all tentative nodes, which are connected to working node. Updateweight if required.6. Find TENTATIVE node with smallest weight. Make this the new workingnode.7. If working node is destination, go to step 8 else go to step 48. Trace back from destination to source./* Program to calculate one Shortest Path Tanenbaum approach*/# include<stdio.h># include<conio.h>/*Total number of nodes in network*/# define NUM_OF_NODES 10/*State of each node*/# define PERMANENT 1# define TENTATIVE 0struct node{unsigned int weight; /*weight of node therefore -1 is max value*/int prev; /*previous node or is connected to*/int state; /*state of the node*/};void main(){int table[NUM_OF_NODES][NUM_OF_NODES] ={ /* A B C D E F G H I J*//*A*/ {0,1,0,0,0,4,0,0,0,0},/*B*/ {1,0,4,0,0,0,0,1,0,0},/*C*/ {0,4,0,3,2,0,0,0,3,0},/*D*/ {0,0,3,0,1,0,0,0,0,0},/*E*/ {0,0,2,1,0,3,0,0,0,1},/*F*/ {4,0,0,0,3,0,1,0,0,0},/*G*/ {0,0,0,0,0,1,0,2,0,2},/*H*/ {0,1,0,0,0,0,2,0,1,0},/*I*/ {0,0,3,0,0,0,0,1,0,2},/*J*/ {0,0,0,0,1,0,2,0,2,0}};/* A B C D E F G H I J*//*interpret as A is connected to B at a weight of 1 astable[A][B]=table[B][A]=1*/int src,dest,i,working_node;/*src is source, dest is destination*/unsigned int min;struct node nodes[NUM_OF_NODES];

10/27

Dept of ECE

CCN Lab Manual

/*initialize all nodes as tentative and having weight of -1 or maximum*/

for(i=0;i<NUM_OF_NODES;++i){nodes[i].state=TENTATIVE;nodes[i].weight=-1;}printf("\nEnter Source:");src=getche();/*convert src character to uppercase then subtract 'A' from itto get src index*/working_node=src=toupper(src)-'A';/*source is working node initially and has prev=-1 and weight=0*/nodes[src].prev=-1;nodes[src].weight=0;printf("\nEnter Destination:");dest=toupper(getche())-'A';do{/*make working node permanent*/nodes[working_node].state=PERMANENT;for(i=0;i<NUM_OF_NODES;++i){if(table[working_node][i]!=0 && nodes[i].state==TENTATIVE){/*if connection exists and Node i is tentative*/if(nodes[working_node].weight+table[working_node][i]<nodes[i].weight){/*If lesser weight is achieved with this node as previous node*/nodes[i].weight=nodes[working_node].weight+table[working_node][i];nodes[i].prev=working_node;/*update weight and previous node*/}}}/*Find minimum weighted Tentative node*/min=-1;for(i=0;i<NUM_OF_NODES;++i){if(nodes[i].state==TENTATIVE && nodes[i].weight<min){min=nodes[i].weight;working_node=i;}}}while(working_node!=dest);/*print shortest path by traversing back through node::prev*/printf("\nShortest Path got--->\n%c",dest+65);do11/27

CCN Lab Manual

3. Encryption and Decryption of a given message

The science and art of manipulating messages to make them secure is calledcryptography. An original message to be transformed is called the plain text and theresulting message after the transformation is called the cipher text . The process ofconverting the plain text into cipher text is called encryption. The reverse process iscalled decryption. The algorithm used for encryption and decryption is often called acipherSubstitution ciphers are a common technique for altering messages in games andpuzzles. Each letter of the alphabet is mapped into another letter. The cipher text isobtained by applying the substitution defined by the mapping to the plain textTransposition ciphers are an other type of encryption scheme . Here the order inwhich the letters appear is altered. The letters may be written into an array in one orderand read out in a different order.Substitution and transposition techniques are easily brokenIn cryptography, the messages to be encrypted; known as plaintext, aretransformed by a function that is parameterized by a key. The output of the encryptionprocess, known as cipher text, is then transmitted, often by messenger or radio. Weassume that the enemy or intruder, hears and accurately copies down the complete ciphertext. However, unlike the intended recipient, he does not know what the decryption key isand so cannot decrypt the cipher text easily. Sometimes the intruder cannot only listen tothe communication channel (passive intruder) but can also record messages and playthem later, inject his own messages, or modify legitimate messages before they get to thereceiver (active intruder). The art of breaking ciphers is called cryptanalysis. The art ofdevising ciphers (cryptography) and breaking them (cryptanalysis) is collectively knownas cryptology. It will often be useful to have a notation for relating plaintext, ciphertextand keys. We will use C=EK(P) to mean that the encryption of the plaintext P using key Kgives the ciphertext C. Similarly, P=DK(C) represents decryption of C to get the plaintextagain. It then follows thatDK(EK(P)) = PFundamental rule of cryptography is that one must assume that the cryptoanalyst knowsthe general method of encryption used.Encryption methods are historically divided into two categories:substitution ciphers and transposition ciphers.Encryption MethodCipher C=Ek(P )Decryption MethodEncryption key-Ek, Decryption key-Dk, Plaintext-P,Plaintext P=DK(EK(P))Substitution CiphersIn a substitution cipher, each letter or group of letters is replaced by another letteror group of letters to disguise it. A way to do this is to have each of the symbols in theplaintext, say the 26 letters for simplicity, map onto some other letter. For example,Plaintext: a b c d e f g h i j k l m n o p q r s t u v w x y zCiphertext: Q W E R T Y U I O P A S D F G H K L Z X C V B N M13/27

Dept of ECE

CCN Lab Manual

This general system is called a mono-alphabetic substitution, with the key being the 26letter string corresponding to the full alphabet. For the key above, the plaintext attackwould be transformed into the ciphertext QZZQEA.Algorithm for Encryption by Substitution Method1. Read data to be encoded2. For every character of dataa. If data is between 'a' and 'z' set encoded data to uppercase character from keyb. If data is between 'A' and 'Z' set encoded data to lowercase character from keyc. If data between '0' and'9' set encoded data to digit from keyd. else copy data into encoded datas array.3. Print encoded data./* Encryption by Substitution method *//* Program to encrypt given data even numbers sequence is a key on which you changedata change all small letters to big and vice versa*/# include<string.h># include<ctype.h># include<stdio.h>void main(){const char sequence[36]="qwertyuiopasdfghjklzxcvbnm4852630791";char data[100]; /*input data*/char encoded[100]; /*encoded data*/int i,len;printf("\nEnter data to be encoded:");gets(data);len=strlen(data);for(i=0;i<len;++i){if(data[i]>='a' && data[i]<='z')/*if small letter subtract from 97 so 'a' becomes 0 and convertsequence[0] to uppercase for 'a'*/encoded[i]=toupper(sequence[(data[i]-97)]);else if(data[i]>='A' && data[i]<='Z')/*if uppercase letter subtract 65 so that 'A' becomes 0 encoded datais seqence['A'-65]*/encoded[i]=sequence[(data[i]-65)];else if(data[i]>='0' && data[i]<='9')/*numbers are present at an offset of 26.. so index sequence onchar-48 + 26... so now '0' will be at 26 or sequence[26]*/encoded[i]=sequence[(data[i]-48)+26];else encoded[i]=data[i];/*else send punctuation marks or special chars normally*/}encoded[len]='\0';printf("Encoded string : %s",encoded);}Output:Enter data to be encoded: Hello World!Encoded string : iTSSG vGKSR!14/27

Dept of ECE

CCN Lab Manual

Algorithm for Decryption by Substitution Method

1. Read encrypted data2. For every character of dataa. Scan through key to see if data is present(i) If present get index of character add it to 'a' if data is uppercase else 'A'if it is in lowercase else '0' if it is a digit.(ii) If not present copy data into decoded datas array.3. Print decoded data./* Decryption by Substitution method *//* Find the given character in key find the location and add that to 'a' or 'A' or '0' as perrequirements */# include<stdio.h># include<ctype.h># include<string.h>void main(){char sequence[36]="qwertyuiopasdfghjklzxcvbnm4852630791";char data[100]; /*input data*/char decoded[100]; /*decoded data*/int i,j,len,present=0;printf("\nEnter data:");gets(data);len=strlen(data);for(i=0;i<len;++i) /*for every element of input data*/{for(j=0;j<36 && !present;++j) /*compare with sequence*/{if(sequence[j]==tolower(data[i])) /*if data matches*//*numbers are not changed by tolower/toupper*/{if(isupper(data[i]))/*numbers return false for this only upper case letters willreturn true*/decoded[i]='a'+j;/*an upper case letter is converted to lower case*/else if(islower(data[i]))decoded[i]='A'+j;/*a lower case letter is converted to upper case*/else /*a digit is encountered*/decoded[i]='0'+(j-26); /*digits are at an offset of 26*/present=1; /*set flag saying digit is present*/}}if(!present)decoded[i]=data[i]; /*assign normal data*/else present=0; /*is present is 1 make it 0 for next time*/}decoded[len]='\0';15/27

Dept of ECE

CCN Lab Manual

printf("\nDecoded string is : %s",decoded);

}Output:Enter data: iTSSG vGKSR!Decoded string is : Hello World!

Transposition CiphersSubstitution ciphers preserve the order of the plaintext symbols but disguise them.Transposition ciphers, in contrast, reorder the letters but do not disguise them. The figurebelow depicts a common transposition cipher, the columnar transposition. The cipher iskeyed by a word or phrase not containing any repeated letters. In this example,MEGABUCK is the key. The purpose of the key is to number the columns, column 1being under the letter closet to the start of the alphabet and so on. The plain text is writtenhorizontally, in rows. The ciphertext is read out by columns, starting with the columnwhose key letter is the lowest.Plain text : pleasetransferonemilliondollarstomyswissbankaccountsixtwotwoMEGABUCK74512836pleasetransferonemilliondollarstomyswissbankaccountsixtwotwoabcdCiphertext:

AFLLSKSOSELAWAIATOOSSCTCLNMOMANTESILYNTWRNNTSOWDPAEDOBUOERIRICXBAlgorithm for Encryption by Transposition Method1. Get sequence of characters in Cipher i.e. MEGABUCK2. Get data to be decoded.3. Arrange data horizontally under MEGABUCK4. Add '.' to make last row complete5. For every column of MEGABUCKa. Find next column to send using sequenceb. Send data under this letter i.e. print the data under this letterc. Jump back to 5 till all columns arent done/* Encryption by Transposition method */# include<string.h># include<stdio.h>void main(){16/27

Dept of ECE

CCN Lab Manual

char data[100];char wrd[]="MEGABUCK";char cipher[8][20]; /*cipher arranges characters under megabuck*/int seq[8]; /*holds MEGABUCK in alphabetical weights ieMEGABUCK6 3 4 0 1 7 2 5*/int i,j,cnt,c;/*to get 63401725*//*compare each character of word with every other char and keep count of number of charactersis bigger than.. i.e. A will be greater than 0 characters B will be greater than 1 character i.e. A so1 and so on...*/for(i=0;i<strlen(wrd);++i){cnt=0;for(j=0;j<strlen(wrd);++j)if(wrd[i]>wrd[j])++cnt;seq[i]=cnt;}printf("\nEnter data:");gets(data);cnt=strlen(data);/* Arrange data under megabuck in order */for(i=0;i<cnt;++i)/* i%strlen(wrd) will correspond to column number i.e. changesfrom 0-7 and back 0-7 as i goes from 0 to cnt-1 resetting to 0 at very 8th chari/strlen(wrd) will go as 0,1,2,3,4, changing by 1 at every 8th character */cipher[i%strlen(wrd)][i/strlen(wrd)]=data[i];if(i%strlen(wrd)!=0) /*if last line is not full*/{for(j=i%strlen(wrd);j<strlen(wrd);++j) /*till last char fill with '.'*/{ cipher[j][i/strlen(wrd)]='.'; ++cnt; }}printf("\nEncrypted data : \n");for(i=0;i<strlen(wrd);++i){for(c=0;c<strlen(wrd);++c)if(seq[c]==i) break;/*find index of value to print first under A i.e. 0 so as i=0 find which seq[c] is 0 print thatnext we search for i=2 or for 2 in seq[c] this is printed out and so on*/for(j=0;j<cnt/strlen(wrd) || j==0;++j)printf("%c",cipher[c][j]);}}Output:Enter data: PLEASE TRANSFER ONE MILLION DOLLARS TO MY SWISS BANKACCOUNT SIX TWO TWOEncrypted data :AS WKTOSFMDTI RLL SCIWLANOR AUTENENSSNNWT LLM CXOPROIAYBOEEIOOSAST

17/27

Dept of ECE

CCN Lab Manual

Algorithm for Decryption by Transposition Method

1. Get sequence of characters in word i.e. MEGABUCK2. Get data to be decoded.3. See if input has a multiple of length of word characters. If its not amultiple, print that it is an error and quit.4. Find position of first character i.e. A5. Put size of data/size of word characters underneath it.6. Do 4-5 for all characters of MEGABUCK in alphabetical order.7. Print all characters row wise starting from M to K./* Decryption by Transposition method */# include<stdio.h># include<string.h>void main(){char wrd[]="MEGABUCK";char data[100];char cipher[8][20];int seq[8];int i,j,cnt,c;for(i=0;i<strlen(wrd);++i){cnt=0;for(j=0;j<strlen(wrd);++j)if(wrd[i]>wrd[j])++cnt;seq[i]=cnt;}/*get weights of MEGABUCK*/printf("\nEnter data:");gets(data);cnt=strlen(data);if(cnt%strlen(wrd)!=0) /*if input is not a multiple of 8 for megabuck*/printf("Error invalid input");else{for(i=0;i<strlen(wrd);++i){for(c=0;c<strlen(wrd);++c)if( seq[c]==i) break;/* Find location where data should be placed i.e. column to place dataunder for 24 letters input there will 4 rows or 0,1,2,3 indices got by cnt/strlen(wrd). iindicates which column weight to feed data under and also number of cnt/strlen(wrd) setof characters have been placed already so now as cnt/strlen(wrd) is 4 for 24 chars... forfirst row 0-3 chars are placed next 4-7 (ie cnt/strlen(wrd) which is 4) + j where j goesfrom 0 to cnt/strlen(wrd) */for(j=0;j<cnt/strlen(wrd);++j)cipher[c][j]=data[i*(cnt/strlen(wrd))+j];}for(j=0;j<strlen(wrd);++j) /* replace trailing '.' with ' ' */{18/27

CCN Lab Manual

4. Find Minimum Spanning Tree of a Subset

In graph theory , a spanning tree is a graph in which there is no loop . In a bridged LAN ,this means creating a topology in which each LAN can be reached from any other LANthrough one path only(no loops). This is done by automatically disabling certain bridges.It is important that these bridges are not physically removed , since a topology changemay require a different set of bridges to be disabled, thus reconfiguring the spanning treedynamicallyA spanning tree is a graph is just a sub-graph that contains all the vertices and is atree. A graph may have many spanning trees. For instance, a complete graph of 4 nodescan have 16 spanning trees. Suppose the edges of the graphs have weights or lengths, theweight of tree is the sum of its edges. Obviously, different trees have different lengths. Aspanning tree includes all the routers but contains no loops. If each router knows which ofits lines belong to the spanning tree, it can copy an incoming broadcast packet onto all thespanning tree lines except the one it arrived on. This method makes excellent use ofbandwidth, generating the absolute minimum number of packets necessary to do the job.The only problem is that each router must have knowledge of some spanning tree for it tobe applicable. Sometimes this information is available (e.g. with link state routing) butsometimes it is not (e.g. with distance vector routing).

A spanning tree of a connected graph G is a connected subgraph of G having no cycles.

Every connected graph has a spanning tree. For example, the following graph has fourdistinct spanning trees.

Spanning Trees:

In general a graph will have very many spanning trees. The weight of a subgraph to besum of all the edge weights in the subgraph. Different spanning trees have differentweights, the minimum spanning tree is the spanning tree with the minimum weight.Example: weights added to the graph above

spanning tree S1 has weight 3+2+4 = 9

CCN Lab Manual

spanning tree S4 has weight 3+4+1 = 8

S3 is the minimum spanning tree of this graph.

Finding the minimum spanning treeThe easiest to understand and probably the best one for solving problems by hand isKruskals algorithm.1. Input number of vertices2. Input the edge weights3. Sort the edge weights in ascending order4. Pick the lowest edge and join the corresponding vertices5. Repeat till edges are marked making sure that there are no closed loops(number of vertices 1)6. Display selected edges.NOTE: In the program given, the variable set is used to eliminate closed loops. Beforejoining two nodes, each nodes set is checked and if found to be the same, the join is notperformed. If the nodes are of different sets then they are joined and then made of thesame set./* Program for finding the Minimum Spanning Tree of a network */# include <stdio.h># include <conio.h>struct node{int set; /* Attribute to indicate which connection the node belongs to */}node[100];struct edge{int first_node,second_node;int distance; /* Distance between the nodes */int selected; /* To denote whether edge is selected */}e[100];int edge_count=0;

CCN Lab Manual

}}void initialise(int total_nodes){int i;for (i=0;i<total_nodes;++i)node[i].set = i; /* Set number to indicate loop */for (i=0;i<edge_count;++i)e[i].selected=-1; /* Edge not selected initially */}void sort_edges(){int i,j;struct edge temp;for (i=0;i<edge_count-1;++i) /* Sorting by Bubble Sort */for (j=0;j<edge_count-i-1;++j)if (e[j].distance>e[j+1].distance){temp=e[j];e[j]=e[j+1];e[j+1]=temp;}}void main(){int total_vertices,i,j,k,m,n,edges_selected=0,nodel,noder;clrscr();printf("Enter the number of vertices : ");scanf("%d",&total_vertices);for (i=0;i<total_vertices;++i)getdata(i,total_vertices);initialise(total_vertices); /* Initialising all nodes and edges */sort_edges();/* Printing sorted order of the edges */clrscr();printf("Sorted order of edges : ");for (i=0;i<edge_count;++i)printf("\nEdge : %d First Node : %c Second Node : %c Distance :%d",i,e[i].first_node+65,e[i].second_node+65,e[i].distance);/* Finding the minimum spanning tree */i=0; /* Initialise i to beginning of the edge array */do{e[i].selected=1; /* Edge is selected */nodel=e[i].first_node; /* Node on the left of the edge */noder=e[i].second_node; /* Node on the right of the edge *//* If the set is the same do not select that edge */if (node[nodel].set==node[noder].set)e[i].selected=-1; /* Deselect the edge */else{22/27

CCN Lab Manual

5. Compute Polynomial Code Checksum for CRC-CCITT

Polynomial codes are extensively used in error detection and correction.Polynomial codes are readily implemented using shift register circuits and therefore arethe most widely implemented error control codes. Polynomial codes involve generatingcheck bits in the form of a cyclic redundancy check (CRC). They are also known as CRCcodes.In polynomial codes the information symbols , the code words and the errorvectors are represented by polynomials with binary coefficients. The k information bits(ik-1, ik-2 , .i1, i0) are used to form the information polynomial of degree (k-1)i(x) = ik-1 xk-1 + ik-2 xk-2 + + i1 x + i0The encoding process takes i(x) and produces a codeword polynomial b(x) thatcontains the information bits and additional check bits and that satisfies a certainpattern. To detect errors , the receiver checks to see whether the pattern is satisfiedThe polynomial code (also known as a cyclic redundancy code or CRC code) iswidely used. Polynomial codes are based upon treating bit strings as representations ofpolynomials with coefficients of 0 and 1 only. A k-bit frame is regarded as the coefficientlist for a polynomial with k terms, ranging from xk-1 to x0. Such a polynomial is said to beof a degree k-1. The high-order (left most) bit is the coefficient of xk-1; the next bit is thecoefficient of xk-2, and so on. For example, 110001 has 6 bits and thus represents a sixterm polynomial with coefficients 1,1,0,0,0 and 1 : x5 + x4 + x0. When the polynomialcode method is employed, the sender and receiver must agree upon a generatorpolynomial, G(x), in advance. Both the high and low-order bits of the generator must be1. To compute the checksum for some frame with m bits, corresponding to thepolynomial M(x), the frame must be longer than the generator polynomial. The idea is toappend a checksum to the end of the frame in such a way that the polynomial representedby the checksummed frame is divisible by G (x). When the receiver gets thechecksummed frame, it tries dividing it by G(x). If there is a remainder, there has been atransmission error.The algorithm for computing checksum is as follows:1. Let r be the degree of G(x). Append r zero bits to the low-order end of the frame, so itnow contains m+r bits and corresponds to the polynomial xr M(x).2. Divide the bit string corresponding to G(X) into the bit string corresponding to xr M(x)using modulo-2 division.3. Subtract the remainder (which is always r or fewer bits) from the bit stringcorresponding to xr M(x) using modulo-2 subtraction. The result is thechecksummed frame to be transmitted. Call its polynomial T(x).The CRC-CCITT polynomial is x16 + x12 + x5 + 1/* C Program to compute polynomial code checksum */# include <stdio.h># include <conio.h># define DEGREE 16 /* Degree of the generator polynomial */int result[30];void calc_CRC(int length){int ccitt[]={1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1}; /* Generator polnomial */25/27