]> CyberLeo.Net >> Repos - FreeBSD/releng/10.2.git/blob - contrib/ipfilter/lib/count4bits.c
- Copy stable/10@285827 to releng/10.2 in preparation for 10.2-RC1
[FreeBSD/releng/10.2.git] / contrib / ipfilter / lib / count4bits.c
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     count4bits(ip)
20         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 }