什么是找到在C中的整数集最高位(MSB)最快/最有效的方法是什么? [英] What is the fastest/most efficient way to find the highest set bit (msb) in an integer in C?
问题描述
如果我有一些整数n,我想知道最显著位的位置(即,如果最低显著位就在右边,我想知道最左侧位是一个位置1),什么是查不到的最快/最有效的方法?
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 the furthest left bit that is a 1), what is the quickest/most efficient method of finding out?
我知道,POSIX支持strings.h一个 FFS()
方法寻找第一个设置位,但似乎并没有得到相应的 FLS()
方法。
I know that POSIX supports a ffs()
method in strings.h to find the first set bit, but there doesn't seem to be a corresponding fls()
method.
是否有这样做,我很想念的一些非常明显的方式?
Is there some really obvious way of doing this that I'm missing?
,你不能用怎么样的情况下POSIX功能的便携性?
What about in cases where you can't use POSIX functions for portability?
编辑:有关在32位和64位架构有效的解决方案是什么(很多code房源看起来他们会只在32位整数工作)
What about a solution that works on both 32 and 64 bit architectures (many of the code listings seem like they'd only work on 32 bit ints).
推荐答案
GCC已的:
-- Built-in Function: int __builtin_clz (unsigned int x)
Returns the number of leading 0-bits in X, starting at the most
significant bit position. If X is 0, the result is undefined.
-- Built-in Function: int __builtin_clzl (unsigned long)
Similar to `__builtin_clz', except the argument type is `unsigned
long'.
-- Built-in Function: int __builtin_clzll (unsigned long long)
Similar to `__builtin_clz', except the argument type is `unsigned
long long'.
我希望他们被翻译成一些合理有效为当前的平台,无论是那些花哨位变换算法中的一个,或单指令。
I'd expect them to be translated into something reasonably efficient for your current platform, whether it be one of those fancy bit-twiddling algorithms, or a single instruction.
这篇关于什么是找到在C中的整数集最高位(MSB)最快/最有效的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!