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