开发者

First position of true value(1) from a bit pattern

开发者 https://www.devze.com 2023-03-25 08:22 出处:网络
For example, if the pattern is as follows: bit[10010][1011][1000] position5432143214321 result214 I want to get the result from right to left po开发者_运维知识库sition as [2] [1] [4]If I understand

For example, if the pattern is as follows:

bit        [10010][1011][1000]
position    54321  4321  4321  
result         2      1  4

I want to get the result from right to left po开发者_运维知识库sition as [2] [1] [4]


If I understand your question correctly, you are looking for a function that returns the index of the least significant 1-bit in an integer. If so, check whether your platform implements the function ffs() ("find first set"). On Linux, you can do man ffs to get the full documentation. On other programming platforms the function may be named differently, e.g. in NVIDIA's CUDA, it exists as a device function __ffs().


Assuming the bit pattern is represented by an int you could do something like

if(bitPattern == 0) {
    return 0;
}

int count = 1;
while(bitPattern % 2 == 0) {
    bitPattern >>= 1;
    count++;
}
return count;


$n = log($x & (~$x+1))/log(2)

~x + 1 is exact the same as -x, as the result of the 2's complement. So why would you use the more complex and slower?

And there are many bithacks to quickly find integer log2x instead of using the much more slower floating point log as above. No slowly divide is needed too. Since x & -x yields only the last bit which is a power of 2, you can use the following function to get log2

unsigned int log2p2(unsigned int v)  // 32-bit value to find the log2 of v
{
    static const unsigned int b[] = {0xAAAAAAAA, 0xCCCCCCCC, 0xF0F0F0F0, 
                                     0xFF00FF00, 0xFFFF0000};
    register unsigned int r = (v & b[0]) != 0;
    for (i = 4; i > 0; i--) // unroll for speed...
    {
        r |= ((v & b[i]) != 0) << i;
    }
}

There are many other ways to calculate log2x which you can find here

So your code is now simply

log2p2(x & -x);
0

精彩评论

暂无评论...
验证码 换一张
取 消