forked from vonj/snippets.org
-
Notifications
You must be signed in to change notification settings - Fork 1
/
arccrc16.c
95 lines (80 loc) · 1.87 KB
/
arccrc16.c
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
** arccrc16.c -- calculate 16-bit CRC for file(s)
** rev. Feb. 1992
** public domain by Raymond Gardner
** Englewood, Colorado
**
** This program uses the same CRC calculation as ARC (SEA) and LHA (Yoshi)
*/
#include <stdio.h>
#include "crc.h"
#define bufsiz (16*1024)
static WORD crc_table[256];
/*
** I determined this function empirically, by examining the
** table for patterns, and programming via trial-and-error.
** Don't ask me how it works or if it can be generalized for
** other CRC polynomials.
*/
void init_crc_table(void)
{
int i, j;
WORD k;
for (i = 0; i < 256; i++)
{
k = 0xC0C1;
for (j = 1; j < 256; j <<= 1)
{
if (i & j)
crc_table[i] ^= k;
k = (k << 1) ^ 0x4003;
}
}
}
/*
** crc_calc() -- calculate cumulative crc-16 for buffer
*/
WORD crc_calc(WORD crc, char *buf, unsigned nbytes)
{
unsigned char *p, *lim;
p = (unsigned char *)buf;
lim = p + nbytes;
while (p < lim)
{
crc = (crc >> 8 ) ^ crc_table[(crc & 0xFF) ^ *p++];
}
return crc;
}
void do_file(char *fn)
{
static char buf[bufsiz];
FILE *f;
int k;
WORD crc;
f = fopen(fn, "rb");
if (f == NULL)
{
printf("%s: can't open file\n", fn);
return;
}
crc = 0;
while ((k = fread(buf, 1, bufsiz, f)) != 0)
crc = crc_calc(crc, buf, k);
fclose(f);
printf("%-14s %04X\n", fn, crc);
}
#ifdef TEST
int main(int argc, char **argv)
{
int i;
if (argc < 2)
{
fprintf(stderr, "Usage: crc filename [filename...]\n");
return EXIT_FAILURE;
}
init_crc_table();
for (i = 1; i < argc; i++)
do_file(argv[i]);
return EXIT_SUCCESS;
}
#endif /* TEST */