What is the fastest/most efficient way to find the highest set bit (msb) in an integer in C?

后端 未结 27 2727
终归单人心
终归单人心 2020-11-22 03:35

If I have some integer n, and I want to know the position of the most significant bit (that is, if the least significant bit is on the right, I want to know the position of

27条回答
  •  一向
    一向 (楼主)
    2020-11-22 04:05

    Woaw, that was many answers. I am not sorry for answering on an old question.

    int result = 0;//could be a char or int8_t instead
    if(value){//this assumes the value is 64bit
        if(0xFFFFFFFF00000000&value){  value>>=(1<<5); result|=(1<<5);  }//if it is 32bit then remove this line
        if(0x00000000FFFF0000&value){  value>>=(1<<4); result|=(1<<4);  }//and remove the 32msb
        if(0x000000000000FF00&value){  value>>=(1<<3); result|=(1<<3);  }
        if(0x00000000000000F0&value){  value>>=(1<<2); result|=(1<<2);  }
        if(0x000000000000000C&value){  value>>=(1<<1); result|=(1<<1);  }
        if(0x0000000000000002&value){  result|=(1<<0);  }
    }else{
      result=-1;
    }
    

    This answer is pretty similar to another answer... oh well.

提交回复
热议问题