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

后端 未结 27 2732
终归单人心
终归单人心 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:03

    Although I would probably only use this method if I absolutely required the best possible performance (e.g. for writing some sort of board game AI involving bitboards), the most efficient solution is to use inline ASM. See the Optimisations section of this blog post for code with an explanation.

    [...], the bsrl assembly instruction computes the position of the most significant bit. Thus, we could use this asm statement:

    asm ("bsrl %1, %0" 
         : "=r" (position) 
         : "r" (number));
    

提交回复
热议问题