位编号 - 查找第一组(ffs)或查找第一组(ffo)Java

时间:2014-01-25 21:31:52

标签: java bit

for (int i = 32; i <= 127; i++) {
}

我将数字int 32转换为二进制数00100000,将数字int 127转换为二进制01111111。我需要从右边读取一个位置的第一个位置(位编号 - 找到第一组(ffs)或找到第一个(ffo)),00100000 - &gt; 6和01111111 - &gt; 1

谢谢!

3 个答案:

答案 0 :(得分:3)

API也是你的朋友:

static int position(int a){
    int pos = Integer.numberOfTrailingZeros(a);
    return pos == 32 ? -1 : pos;
}

答案 1 :(得分:2)

查找此号码的简单方法如下:

int findLowestSetBit(int n) {
    for (int i = 0 ; i != 32 ; i++) {
        if ((n & (1 << i)) != 0) {
            return i;
        }
    }
    return -1;
}

但是,它不是最快的,因为它会“线性地”搜索一个设置位。您可以使用以下代码copied from the bit hack page并行执行此操作:

int v;      // 32-bit word input to count zero bits on right
int c = 32; // c will be the number of zero bits on the right
v &= -v;
if (v != 0) c--;
if ((v & 0x0000FFFF) != 0) c -= 16;
if ((v & 0x00FF00FF) != 0) c -= 8;
if ((v & 0x0F0F0F0F) != 0) c -= 4;
if ((v & 0x33333333) != 0) c -= 2;
if ((v & 0x55555555) != 0) c -= 1;

答案 2 :(得分:0)

找到Function你可以使用递归&amp; leading zeros

我在这里回答类似的问题:

bit wise shift

或使用count leading zeros (clz) or number of leading zeros (nlz) in Java,其中包含一些示例:

Divine & Conquer Algorithm