xref: /csrg-svn/usr.bin/cksum/sum1.c (revision 47797)
1*47797Sbostic /*-
2*47797Sbostic  * Copyright (c) 1991 The Regents of the University of California.
3*47797Sbostic  * All rights reserved.
4*47797Sbostic  *
5*47797Sbostic  * %sccs.include.redist.c%
6*47797Sbostic  */
7*47797Sbostic 
8*47797Sbostic #ifndef lint
9*47797Sbostic static char sccsid[] = "@(#)sum1.c	5.1 (Berkeley) 04/04/91";
10*47797Sbostic #endif /* not lint */
11*47797Sbostic 
12*47797Sbostic #include <sys/types.h>
13*47797Sbostic #include <unistd.h>
14*47797Sbostic 
15*47797Sbostic csum1(fd, cval, clen)
16*47797Sbostic 	register int fd;
17*47797Sbostic 	u_long *cval, *clen;
18*47797Sbostic {
19*47797Sbostic 	register u_long total;
20*47797Sbostic 	register int nr;
21*47797Sbostic 	register u_int crc;
22*47797Sbostic 	register u_char *p;
23*47797Sbostic 	u_char buf[8192];
24*47797Sbostic 
25*47797Sbostic 	/*
26*47797Sbostic 	 * 16-bit checksum, rotating right before each addition;
27*47797Sbostic 	 * overflow is discarded.
28*47797Sbostic 	 */
29*47797Sbostic 	crc = total = 0;
30*47797Sbostic 	while ((nr = read(fd, buf, sizeof(buf))) > 0)
31*47797Sbostic 		for (total += nr, p = buf; nr--; ++p) {
32*47797Sbostic 			if (crc & 1)
33*47797Sbostic 				crc |= 0x10000;
34*47797Sbostic 			crc = ((crc >> 1) + *p) & 0xffff;
35*47797Sbostic 		}
36*47797Sbostic 	if (nr < 0)
37*47797Sbostic 		return(1);
38*47797Sbostic 
39*47797Sbostic 	*cval = crc;
40*47797Sbostic 	*clen = total;
41*47797Sbostic 	return(0);
42*47797Sbostic }
43