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