第二最低有效设定位的索引

时间:2014-02-11 16:09:12

标签: python bit-manipulation

如何获得第二个最低位的索引?例如,如果x=136这应该是8(使用1索引)。

索引来自最低位。例如:

bin(136)
'0b10001000'

如果x=88输出应为5

为了使这项工作正常,我们还需要测试设置的位数至少为2.幸运的是bin(x).count('1')会这样做。

return index of least significant bit in Python找到最低有效位的答案(尽管至少有一个答案似乎是错误的)。

5 个答案:

答案 0 :(得分:1)

如果您可以获得最不重要的位置,只需将其从变量中删除并再次应用相同的推理。

get_least( x - ( 1 << get_least(x) ) ) 

(假设get_least返回0个索引位数)

或以功能形式

def get_least(x):
  return ...........

def get_second_least(x):
  return get_least( x - ( 1 << ( get_least(x) ) ) )

答案 1 :(得分:1)

您可以迭代从lsb到msb的位。您也可以使用它来获得第n位。

def get_nth_least_bit(x, n):
    sum = 0
    for i in range(0,x.bit_length()):
        sum += (x >> i) & 1
        if sum == n :
                return i + 1
    return -1

注意:bit_length()仅在python 2.7和3

答案 2 :(得分:1)

我不会说python,但这就是我用c语法做的方法。移植应该很容易。

    int get2ndMSBIndex(int x) {

        x = x & (x - 1);   // Turn off rightmost 1-bit
        x = x & (-x);      // Isolate rightmost 1-bit. will be zero if none

        int pos = 0;

        while (x != 0) {
            x = x >> 1;
            pos++;
        }

        return pos;
    }

答案 3 :(得分:1)

屏蔽最低有效位,然后找到最低有效位。

借用answer to the other question

def fss(x):
    """Returns the index, counting from 1, of the
    second least significant set bit in `x`.
    """
    x = x & (x-1)
    return (x&-x).bit_length()

答案 4 :(得分:0)

好吧,为了收集第n组LSB,你可能想分开去除较低的LSB,并实际找到索引。要掩盖一点,你需要它的价值;你不需要计算它的索引。您可以将索引查找推迟到结束。即:

x = 0x188
# Find the value of the lowest bit, to clear.
least_power_of_2_x = ((x ^ (x-1)) + 1) >> 1
least_power_of_2_x
0x8

# Clear that bit
x = x ^ least_power_of_2_x
x
0x180

# Use same algorithm to find the next least
next_least = ((x ^ (x-1)) + 1) >> 1
next_least
0x80

# Now, you have the bit you actually care about. Find its index, 1-indexed.
next_least_index = len(bin(next_least)) - 2
next_least_index
8
相关问题