xref: /titanic_44/usr/src/lib/libresolv2/common/isc/bitncmp.c (revision 7c478bd95313f5f23a4c958a745db2134aa03244)
1 /*
2  * Copyright 1997-2002 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 
6 /*
7  * Copyright (c) 1996,1999 by Internet Software Consortium.
8  *
9  * Permission to use, copy, modify, and distribute this software for any
10  * purpose with or without fee is hereby granted, provided that the above
11  * copyright notice and this permission notice appear in all copies.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
14  * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
15  * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
16  * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
17  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
18  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
19  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
20  * SOFTWARE.
21  */
22 
23 #pragma ident	"%Z%%M%	%I%	%E% SMI"
24 
25 #if defined(LIBC_SCCS) && !defined(lint)
26 static const char rcsid[] = "$Id: bitncmp.c,v 1.7 2001/05/29 05:49:23 marka Exp $";
27 #endif
28 
29 #include "port_before.h"
30 
31 #include <sys/types.h>
32 
33 #include <string.h>
34 
35 #include "port_after.h"
36 
37 #include <isc/misc.h>
38 
39 /*
40  * int
41  * bitncmp(l, r, n)
42  *	compare bit masks l and r, for n bits.
43  * return:
44  *	-1, 1, or 0 in the libc tradition.
45  * note:
46  *	network byte order assumed.  this means 192.5.5.240/28 has
47  *	0x11110000 in its fourth octet.
48  * author:
49  *	Paul Vixie (ISC), June 1996
50  */
51 int
52 bitncmp(const void *l, const void *r, int n) {
53 	u_int lb, rb;
54 	int x, b;
55 
56 	b = n / 8;
57 	x = memcmp(l, r, b);
58 	if (x)
59 		return (x);
60 
61 	lb = ((const u_char *)l)[b];
62 	rb = ((const u_char *)r)[b];
63 	for (b = n % 8; b > 0; b--) {
64 		if ((lb & 0x80) != (rb & 0x80)) {
65 			if (lb & 0x80)
66 				return (1);
67 			return (-1);
68 		}
69 		lb <<= 1;
70 		rb <<= 1;
71 	}
72 	return (0);
73 }
74