xref: /onnv-gate/usr/src/cmd/ipf/lib/common/count4bits.c (revision 0:68f95e015346)
1*0Sstevel@tonic-gate /*
2*0Sstevel@tonic-gate  * Copyright (C) 1993-2001 by Darren Reed.
3*0Sstevel@tonic-gate  *
4*0Sstevel@tonic-gate  * See the IPFILTER.LICENCE file for details on licencing.
5*0Sstevel@tonic-gate  *
6*0Sstevel@tonic-gate  * $Id: count4bits.c,v 1.1 2002/06/15 04:46:39 darrenr Exp $
7*0Sstevel@tonic-gate  */
8*0Sstevel@tonic-gate 
9*0Sstevel@tonic-gate #include "ipf.h"
10*0Sstevel@tonic-gate 
11*0Sstevel@tonic-gate 
12*0Sstevel@tonic-gate /*
13*0Sstevel@tonic-gate  * count consecutive 1's in bit mask.  If the mask generated by counting
14*0Sstevel@tonic-gate  * consecutive 1's is different to that passed, return -1, else return #
15*0Sstevel@tonic-gate  * of bits.
16*0Sstevel@tonic-gate  */
count4bits(ip)17*0Sstevel@tonic-gate int	count4bits(ip)
18*0Sstevel@tonic-gate u_int	ip;
19*0Sstevel@tonic-gate {
20*0Sstevel@tonic-gate 	int cnt = 0, i, j;
21*0Sstevel@tonic-gate 	u_int ipn;
22*0Sstevel@tonic-gate 
23*0Sstevel@tonic-gate 	ip = ipn = ntohl(ip);
24*0Sstevel@tonic-gate 	for (i = 32; i; i--, ipn *= 2)
25*0Sstevel@tonic-gate 		if (ipn & 0x80000000)
26*0Sstevel@tonic-gate 			cnt++;
27*0Sstevel@tonic-gate 		else
28*0Sstevel@tonic-gate 			break;
29*0Sstevel@tonic-gate 	ipn = 0;
30*0Sstevel@tonic-gate 	for (i = 32, j = cnt; i; i--, j--) {
31*0Sstevel@tonic-gate 		ipn *= 2;
32*0Sstevel@tonic-gate 		if (j > 0)
33*0Sstevel@tonic-gate 			ipn++;
34*0Sstevel@tonic-gate 	}
35*0Sstevel@tonic-gate 	if (ipn == ip)
36*0Sstevel@tonic-gate 		return cnt;
37*0Sstevel@tonic-gate 	return -1;
38*0Sstevel@tonic-gate }
39