beautypg.com

Calculating crc crc example code – INFICON PSG55x ATM to Medium Vacuum Gauge (RS232C / RS485C) User Manual

Page 10

background image

10

tira59e1 (2010-07) RS232C.cp

The data packages are secured with CRC16 in Little Endian.

CRC polynominal

0x8408

CRC initial value

0xFFFF


To illustrate how the checksum can be calculated and verified, an example of a
code is given below:

using

System;

class

Program

{

static

void

Main()

{

// the following test array is a valid pcg5xx frame with crc16 at the end

byte

[] arr =

new

byte

[] { 0x00, 0x00, 0x00, 0x05, 0x01, 0x00, 0xDD, 0x00, 0x00, 0xAB, 0x21};

UInt16

crc;

Boolean

b;

// Calculate the crc of the test array arr, of course without crc (therefore length minus 2)

crc =

Crc16

.Create(arr, (

Byte

)(arr.Length - 2));

// Check, if the test array has a correct crc at the end (it is correct, therefore the returnvalue is

true)

b =

Crc16

.Check(arr, (

Byte

)arr.Length);

}
}

public

class

Crc16

{

// initial value for crc16

public

static

UInt16

inital = 0xFFFF;


// function to create a crc16

public

static

UInt16

Create(

Byte

[] buffer,

Byte

length)

{

UInt16

crc16 =

new

UInt16

();

UInt16

i = 0;


// Initial Value for CRC calculation

crc16 =

Crc16

.inital;


while

(i < length)

{
crc16 = (

UInt16

)((

Crc16

.crc16Tab[(crc16 ^ buffer[i++]) & (

Byte

)0xFF]) ^ (crc16 >> 8));

}

return

crc16;

}

// function to check a buffer with a crc16 at the end

public

static

Boolean

Check(

Byte

[] buffer,

Byte

length)

{

UInt16

crc16 =

Crc16

.inital;

UInt16

i = 0;

// calculate crc for the buffer without crc

while

(i < length)

{
crc16 = (

UInt16

)((

Crc16

.crc16Tab[(crc16 ^ buffer[i++]) & (

Byte

)0xFF]) ^ (crc16 >> 8));

}

if

(crc16 == 0)

{

return

true

;

}

return

false

;

}

// crc array

public

static

UInt16

[] crc16Tab =

{
0x0000, 0x1189, 0x2312, 0x329B, 0x4624, 0x57AD, 0x6536, 0x74BF,
0x8C48, 0x9DC1, 0xAF5A, 0xBED3, 0xCA6C, 0xDBE5, 0xE97E, 0xF8F7,
0x1081, 0x0108, 0x3393, 0x221A, 0x56A5, 0x472C, 0x75B7, 0x643E,
0x9CC9, 0x8D40, 0xBFDB, 0xAE52, 0xDAED, 0xCB64, 0xF9FF, 0xE876,
0x2102, 0x308B, 0x0210, 0x1399, 0x6726, 0x76AF, 0x4434, 0x55BD,
0xAD4A, 0xBCC3, 0x8E58, 0x9FD1, 0xEB6E, 0xFAE7, 0xC87C, 0xD9F5,
0x3183, 0x200A, 0x1291, 0x0318, 0x77A7, 0x662E, 0x54B5, 0x453C,
0xBDCB, 0xAC42, 0x9ED9, 0x8F50, 0xFBEF, 0xEA66, 0xD8FD, 0xC974,
0x4204, 0x538D, 0x6116, 0x709F, 0x0420, 0x15A9, 0x2732, 0x36BB,
0xCE4C, 0xDFC5, 0xED5E, 0xFCD7, 0x8868, 0x99E1, 0xAB7A, 0xBAF3,
0x5285, 0x430C, 0x7197, 0x601E, 0x14A1, 0x0528, 0x37B3, 0x263A,
0xDECD, 0xCF44, 0xFDDF, 0xEC56, 0x98E9, 0x8960, 0xBBFB, 0xAA72,

Calculating CRC

CRC Example Code

This manual is related to the following products: