Create a mask that marks the most significant set bit, using only bitwise operators

前端 未结 5 1392
慢半拍i
慢半拍i 2020-12-18 23:43

This was part of a larger programming assignment that was due for me last night. Couldn\'t figure out this problem, but I\'m curious as to how it could be solved.

Th

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-19 00:18

    Fill all of the bits to the right of the most significant one by shifting and OR'ing:

    0b 0010 0000 0000 0000 0100 0000 0000 0000
    0b 0011 0000 0000 0000 0110 0000 0000 0000
    0b 0011 1100 0000 0000 0111 1000 0000 0000
    0b 0011 1111 1100 0000 0111 1111 1000 0000
    0b 0011 1111 1111 1111 1111 1111 1111 1111
    

    Then shift right and add 1 to leave the most significant one:

    0b 0001 1111 1111 1111 1111 1111 1111 1111
    0b 0010 0000 0000 0000 0000 0000 0000 0000
    

    Code:

    int greatestBitPos(int x) {
      int is_nonzero = (x != 0);
      x = x | (x >> 1);
      x = x | (x >> 2);
      x = x | (x >> 4);
      x = x | (x >> 18);
      x = x | (x >> 16);
      return (is_nonzero * ((x >> 1) + 1));
    }
    

提交回复
热议问题