# Visual C# 2005 GuideError Detection Algorithms

## Introduction

The page, Error Detection & Correction describes some error detection techniques used when character data is transmitted.

The algorithms are Pseudocode, you can do the conversion.

## Single Parity Bit

Parity bits are set to make sure that the total number of on bits in a bit pattern is ether odd or even. You choose the method before you start. In this case, we will use odd parity.

### Calculating A Parity Bit

``` (string) Function calculateOddParity(string bitPattern) { Declare thisBit As char Declare numOn As int Declare parityEncoded As string FOR stepper ← 0 TO bitPattern.Length - 1    thisBit ← bitPattern[stepper]    IF thisBit = '1' THEN numOn ← numOn + 1 Endfor IF numOn Mod 2 = 1 THEN    parityEncoded ← "0" + bitPattern ELSE    parityEncoded ← "1" + bitPattern EndIf Return parityEncoded } ```

Notice how we use the modulus to determine whether or not a number is even. If numOn Mod 2 is 1, then we have an odd number so we use a 0 for the parity bit. Otherwise we use a 1. If you swap these values around, you check for even parity instead.

The length of the input string is used for flexibility here - you should really check that you have a 7 character string containing only 1s and 0s.

### Checking Parity

``` (bool) Function checkOddParity(string bitPattern) { Declare thisBit As char Declare numOn As int Declare valid As bool FOR stepper ← 0 TO bitPattern.Length - 1    thisBit ← bitPattern[stepper]    IF thisBit = '1' THEN numOn ← numOn + 1 Endfor IF numOn Mod 2 = 1 THEN    valid ← TRUE ELSE    valid ← FALSE EndIf Return valid } ```

An alternate method to check is to find bitPattern.substring(1,7) - everything except the first character (the parity bit). Pass this value to the calculateOddParity function and compare the result to the original input.