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