maint: update copyright
[gnulib.git] / lib / ffs.c
1 /* ffs.c -- find the first set bit in a word.
2    Copyright (C) 2011-2014 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 /* Written by Eric Blake.  */
18
19 #include <config.h>
20
21 /* Specification.  */
22 #include <strings.h>
23
24 #include <limits.h>
25
26 int
27 ffs (int i)
28 {
29 #if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
30   return __builtin_ffs (i);
31 #else
32   /* http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup
33      gives this deBruijn constant for a branch-less computation, although
34      that table counted trailing zeros rather than bit position.  This
35      requires 32-bit int, we fall back to a naive algorithm on the rare
36      platforms where that assumption is not true.  */
37   if (CHAR_BIT * sizeof i == 32)
38     {
39       static unsigned int table[] = {
40         1, 2, 29, 3, 30, 15, 25, 4, 31, 23, 21, 16, 26, 18, 5, 9,
41         32, 28, 14, 24, 22, 20, 17, 8, 27, 13, 19, 7, 12, 6, 11, 10
42       };
43       unsigned int u = i;
44       unsigned int bit = u & -u;
45       return table[(bit * 0x077cb531U) >> 27] - !i;
46     }
47   else
48     {
49       unsigned int j;
50       for (j = 0; j < CHAR_BIT * sizeof i; j++)
51         if (i & (1U << j))
52           return j + 1;
53       return 0;
54     }
55 #endif
56 }