1 /*
2 * Copyright (C) 2001, 2002, and 2003 Roy Keene
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17 *
18 * email: dact@rkeene.org
19 */
20
21 #include "dact.h"
22 #include "crc.h"
23
elfcrc(const uint32_t start,const unsigned char * name,const uint32_t n)24 uint32_t elfcrc(const uint32_t start, const unsigned char *name, const uint32_t n) {
25 uint32_t i, h, g=0;
26
27 h = start;
28 for (i=0;i<n;i++) {
29 h = (h << 4) + (*name++);
30 g = h & 0xf0000000;
31 if (g) h ^= (g >> ((sizeof(g)*8)-8));
32 h &= ~g;
33 }
34
35 return(h);
36 }
37
38 /* Adler-32 is composed of two sums accumulated per byte: s1 is the sum
39 of all bytes, s2 is the sum of all s1 values. Both sums are done
40 modulo 65521. s1 is initialised to 1, s2 to zero.
41 */
crc(const uint32_t prev,unsigned char * val,const uint32_t n)42 uint32_t crc(const uint32_t prev, unsigned char *val, const uint32_t n) {
43 uint32_t ret=prev, i;
44 uint16_t s1, s2;
45 unsigned char *s=val;
46
47 if (ret==0) ret=1;
48
49 s1=ret&0xffff;
50 s2=(ret>>16)&0xffff;
51 for (i=0; i<n; i++) {
52 s1 = (s1 + *s) % 65521;
53 s2 = (s1 + s2) % 65521;
54 s++;
55 }
56 ret=(s2<<16)|s1;
57 return(ret);
58 }
59