aboutsummaryrefslogtreecommitdiff
path: root/crc16.c
blob: d0b5f0f2e7383807ba3f85310b9d44ccff47ca14 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* $Id$ */
/*
 * this source code is based on Rex and Binstock which, in turn,
 * acknowledges William James Hunt.
 * source: http://www.darkridge.com/~jpr5/archive/alg/node191.html
 */

#include <stdlib.h>
#include <stdio.h>

unsigned int crc_16_table[16] = {
	0x0000, 0xcc01, 0xd801, 0x1400, 0xf001, 0x3c00, 0x2800, 0xe401,
	0xa001, 0x6c00, 0x7800, 0xb401, 0x5000, 0x9c01, 0x8801, 0x4400
};

unsigned short int
get_crc_16(int start, char *p, int n)
{
	unsigned short int crc;
	int r;

	for (crc = start; n-- > 0; ++p) {
		/* compute checksum of lower four bits of *p */
		r = crc_16_table[crc & 0x0f];
		crc = (crc >> 4) & 0x0fff;
		crc ^= r ^ crc_16_table[*p & 0x0f];

		/* compute checksum of upper four bits of *p */
		r = crc_16_table[crc & 0x0f];
		crc = (crc >> 4) & 0x0fff;
		crc ^= r ^ crc_16_table[(*p >> 4) & 0x0f];
	}

	return crc;
}