Guest User

Untitled

a guest
Jan 22nd, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. int a = 12;
  2.  
  3. int set_bit = n ^ (n&(n-1));
  4.  
  5. int pos = n ^ (n&(n-1));
  6.  
  7. x & -x
  8. // or
  9. x & (~x + 1)
  10.  
  11. x &= x - 1
  12. // or
  13. x -= x & -x // rhs is rightmost set bit
  14.  
  15. x: leading bits 1 all 0
  16. ~x: reversed leading bits 0 all 1
  17. ~x + 1 or -x: reversed leading bits 1 all 0
  18. x & -x: all 0 1 all 0
  19.  
  20. // example for get rightmost set bit
  21. x: 01110000
  22. ~x: 10001111
  23. -x or ~x + 1: 10010000
  24. x & -x: 00010000
  25.  
  26. // example for unset rightmost set bit
  27. x: 01110000
  28. x-1: 01101111
  29. x & (x-1): 01100000
  30.  
  31. #include <limits.h>
  32.  
  33. int last_set_pos(int a) {
  34. for (int i = 0; i < sizeof a * CHAR_BIT; ++i) {
  35. if (a & (0x1 << i)) return i;
  36. }
  37. return -1; // a == 0
  38. }
  39.  
  40. int rightMostSet(int a){
  41. if (!a) return -1; //means there isn't any 1-bit
  42. int i=0;
  43. while(a&1==0){
  44. i++;
  45. a>>1;
  46. }
  47. return i;
  48. }
Add Comment
Please, Sign In to add comment