Ruby 4.1.0dev (2026-08-15 revision d1c079751b80352d347452c8d134ffb177838adb)
ffs.c
1/* ffs.c - find first set bit */
2/* ffs() is defined by Single Unix Specification. */
3
4#include <limits.h>
5#include "ruby/config.h"
6
7int ffs(int arg)
8{
9 unsigned int x = (unsigned int)arg;
10 int r;
11
12 if (x == 0)
13 return 0;
14
15 r = 1;
16
17#if 32 < SIZEOF_INT * CHAR_BIT
18 if ((x & 0xffffffff) == 0) {
19 x >>= 32;
20 r += 32;
21 }
22#endif
23
24 if ((x & 0xffff) == 0) {
25 x >>= 16;
26 r += 16;
27 }
28
29 if ((x & 0xff) == 0) {
30 x >>= 8;
31 r += 8;
32 }
33
34 if ((x & 0xf) == 0) {
35 x >>= 4;
36 r += 4;
37 }
38
39 if ((x & 0x3) == 0) {
40 x >>= 2;
41 r += 2;
42 }
43
44 if ((x & 0x1) == 0) {
45 x >>= 1;
46 r += 1;
47 }
48
49 return r;
50}