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