原来发过搜索第一位的帖子,这次算再补充一下吧。以下取自网络,作者不详。
1 #ifdef __GNUC__
2
3 #if (defined _WIN64 || defined __x86_64__)
4
5 /**
6 * ../bit_scan_forward
7 * @return index (0..63) of least significant one bit
8 */
9 unsigned bit_scan_forward(unsigned long long x)
10 {
11 asm("bsfq %0, %0" : "=r" (x) : "0" (x));
12 return unsigned(x);
13 }
14
15 /**
16 * bit_scan_reverse
17 * @return index (0..63) of most significant one bit
18 */
19 unsigned bit_scan_reverse(unsigned long long x)
20 {
21 asm("bsrq %0, %0" : "=r" (x) : "0" (x));
22 return unsigned(x);
23 }
24
25 #elif (defined _WIN32) || (defined __linux__)
26
27 /**
28 * ../bit_scan_forward
29 * @return index (0..63) of least significant one bit
30 */
31 unsigned bit_scan_forward(unsigned long long x)
32 {
33 asm("bsf %0, %0" : "=r" (x) : "0" (x));
34 return unsigned(x);
35 }
36
37 /**
38 * bit_scan_reverse
39 * @return index (0..63) of most significant one bit
40 */
41 unsigned bit_scan_reverse(unsigned long long x)
42 {
43 asm("bsr %0, %0" : "=r" (x) : "0" (x));
44 return unsigned(x);
45 }
46
47 #endif
48
49 #endif