c++bit-manipulationbitbuilt-infindfirst

Getting the index of the leftmost active bit in an integer instantly


How would I scan an integer (in binary) from left to right instead of right to left? I know that I can start from the left and try every bit, and then record the leftmost bit, but is there a faster way? Is there a built-in function that can instantly find the leftmost active bit (that is a 1) in an integer?

I know that for right to left, I can do something like

int myInt = 1234;
for(int i = 0; i < 32; i++) {
  int curr_bit = myInt & (1 << i);
  // do something with curr_bit
}

But, I want to start off at the leftmost available bit, and I want its number "x" so that 1 << x will point to that exact digit (Just as a side note, I am trying to implement repeated squaring, and I need this in my code).

Any help would be greatly appreciated!


Solution

  • iBug's answer is very interesting, and I had never thought of doing it this way. If you're doing huge calculations where you want to find the leftmost digit many many times, I would recomment __builtin_clz in c++11. If you perform the snippet

    for(int i = 31 - __builtin_clz; i >= 0; i--) {
        int left_most_bit = myInt & (1 << i);
    }
    

    This will start from the left_most_bit and work it's way to the right. Hope this helps! Implementation of __builtin_clz