Get the position where the lowest bit of an integer variable is 1
#define BIT_LOW_BIT(y) (((y)&BIT(0)) ? 0 : (((y)&BIT(1)) ? 1 : (((y)&BIT(2)) ? 2 : (((y)&BIT(3)) ? 3 : \
(((y)&BIT(4)) ? 4 : (((y)&BIT(5)) ? 5 : (((y)&BIT(6)) ? 6 : (((y)&BIT(7)) ? 7 : \
(((y)&BIT(8)) ? 8 : (((y)&BIT(9)) ? 9 : (((y)&BIT(10)) ? 10 : (((y)&BIT(11)) ? 11 : \
(((y)&BIT(12)) ? 12 : (((y)&BIT(13)) ? 13 : (((y)&BIT(14)) ? 14 : (((y)&BIT(15)) ? 15 : \
(((y)&BIT(16)) ? 16 : (((y)&BIT(17)) ? 17 : (((y)&BIT(18)) ? 18 : (((y)&BIT(19)) ? 19 : \
(((y)&BIT(20)) ? 20 : (((y)&BIT(21)) ? 21 : (((y)&BIT(22)) ? 22 : (((y)&BIT(23)) ? 23 : \
(((y)&BIT(24)) ? 24 : (((y)&BIT(25)) ? 25 : (((y)&BIT(26)) ? 26 : (((y)&BIT(27)) ? 27 : \
(((y)&BIT(28)) ? 28 : (((y)&BIT(29)) ? 29 : (((y)&BIT(30)) ? 30 : (((y)&BIT(31)) ? 31 : 32 \
))))))))))))))))))))))))))))))))
This macro determines the position of the lowest bit by performing a series of bit-AND operations and nesting of ternary operators on the variable y. It starts from the lowest bit and checks whether each bit is 1 in turn. If it is 1, it returns the corresponding position; if not, it enters the judgment of the next bit until it finds the position of the lowest bit. Returns 32 if all bits are 0.
#include <stdio.h>
#define BIT(n) (1 << (n))
#define BIT_LOW_BIT(y) (((y)&BIT(0)) ? 0 : (((y)&BIT(1)) ? 1 : (((y)&BIT(2)) ? 2 : (((y)&BIT(3)) ? 3 : \
(((y)&BIT(4)) ? 4 : (((y)&BIT(5)) ? 5 : (((y)&BIT(6)) ? 6 : (((y)&BIT(7)) ? 7 : \
(((y)&BIT(8)) ? 8 : (((y)&BIT(9)) ? 9 : (((y)&BIT(10)) ? 10 : (((y)&BIT(11)) ? 11 : \
(((y)&BIT(12)) ? 12 : (((y)&BIT(13)) ? 13 : (((y)&BIT(14)) ? 14 : (((y)&BIT(15)) ? 15 : \
(((y)&BIT(16)) ? 16 : (((y)&BIT(17)) ? 17 : (((y)&BIT(18)) ? 18 : (((y)&BIT(19)) ? 19 : \
(((y)&BIT(20)) ? 20 : (((y)&BIT(21)) ? 21 : (((y)&BIT(22)) ? 22 : (((y)&BIT(23)) ? 23 : \
(((y)&BIT(24)) ? 24 : (((y)&BIT(25)) ? 25 : (((y)&BIT(26)) ? 26 : (((y)&BIT(27)) ? 27 : \
(((y)&BIT(28)) ? 28 : (((y)&BIT(29)) ? 29 : (((y)&BIT(30)) ? 30 : (((y)&BIT(31)) ? 31 : 32 \
))))))))))))))))))))))))))))))))
int main()
{
int num = 10; /* 二进制表示:00000000000000000000000000001010 */
int lowBit = BIT_LOW_BIT(num);
printf("最低位的位置:%d\n", lowBit);
return 0;
}
printout
最低位的位置:1