xref: /openbsd-src/lib/libc/string/ffs.c (revision a28daedfc357b214be5c701aa8ba8adb29a7f1c2)
1 /*	$OpenBSD: ffs.c,v 1.7 2005/08/08 08:05:37 espie Exp $	*/
2 
3 /*
4  * Public domain.
5  * Written by Dale Rahn.
6  */
7 
8 #if !defined(_KERNEL) && !defined(_STANDALONE)
9 #include <string.h>
10 #else
11 #include <lib/libkern/libkern.h>
12 #endif
13 
14 /*
15  * ffs -- vax ffs instruction
16  */
17 int
18 ffs(int mask)
19 {
20 	int bit;
21 	unsigned int r = mask;
22 	static const signed char t[16] = {
23 		-28, 1, 2, 1,
24 		  3, 1, 2, 1,
25 		  4, 1, 2, 1,
26 		  3, 1, 2, 1
27 	};
28 
29 	bit = 0;
30 	if (!(r & 0xffff)) {
31 		bit += 16;
32 		r >>= 16;
33 	}
34 	if (!(r & 0xff)) {
35 		bit += 8;
36 		r >>= 8;
37 	}
38 	if (!(r & 0xf)) {
39 		bit += 4;
40 		r >>= 4;
41 	}
42 
43 	return (bit + t[ r & 0xf ]);
44 }
45