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