Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int a = 12;
- int set_bit = n ^ (n&(n-1));
- int pos = n ^ (n&(n-1));
- x & -x
- // or
- x & (~x + 1)
- x &= x - 1
- // or
- x -= x & -x // rhs is rightmost set bit
- x: leading bits 1 all 0
- ~x: reversed leading bits 0 all 1
- ~x + 1 or -x: reversed leading bits 1 all 0
- x & -x: all 0 1 all 0
- // example for get rightmost set bit
- x: 01110000
- ~x: 10001111
- -x or ~x + 1: 10010000
- x & -x: 00010000
- // example for unset rightmost set bit
- x: 01110000
- x-1: 01101111
- x & (x-1): 01100000
- #include <limits.h>
- int last_set_pos(int a) {
- for (int i = 0; i < sizeof a * CHAR_BIT; ++i) {
- if (a & (0x1 << i)) return i;
- }
- return -1; // a == 0
- }
- int rightMostSet(int a){
- if (!a) return -1; //means there isn't any 1-bit
- int i=0;
- while(a&1==0){
- i++;
- a>>1;
- }
- return i;
- }
Add Comment
Please, Sign In to add comment