最低阶位的索引 [英] Index of lowest order bit

查看:119
本文介绍了最低阶位的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到获得的最低阶位的指数很长很长的最快方法。即:

  00101001001000  - > 3

涉及循环和变速解是太慢了。即:

  INT I;
如果(位== 0ULL){
  我= 64;
}其他{
  对于(i = 0;!(位&安培; 1ULL);我++)
    比特GT;> = 1;
}

编辑:使用情况信息

使用ffsll不能真正降低它的使用,但这里是(简化当然)功能。它只是通过指数迭代,并且做了他们。这个功能也许是在我的整个应用使用最广泛的功能,尽管有很多它的价值的缓存。它在我的的Alpha-Beta 的搜索引擎。

 而(位){
  指数= ffsll(比特);
  DoSomething的(指数);
  指数&安培; =指数1;
}


解决方案

英特尔有专门寻找任何最低或最高顺序设置位指令。 BSF 好像你所需要的。至于纯C语言做,也许位摆弄黑客网页有你需要的。

至少,你可以用半字节或字节的表来加快速度。像这样的东西(证明对于int,但容易改变到龙龙如果需要)。

  / *
0000 - 0
0001 - 1
0010 - 2
0011 - 1
0100 - 3
0101 - 1
0110 - 2
0111 - 1
1000 - 4
1001 - 1
1010 - 2
1011 - 1
1100 - 3
1101 - 1
1110 - 2
1111 - 1
* /INT FFS(int i)以{
    INT RET = 0;
    INT J = 0;
    静态const int的_ffs_tab [] =
    {0,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1};    而((I = 0)及!及(保留== 0)){
    RET = _ffs_tab [I和为0x0F];    如果(保留大于0){
    突破;
    }    I>> = 4;
    J + = 4;    / *技术上的符号位可以留,所以我们掩盖它,以确保* /
    I和= INT_MAX;
    }    如果(保留!= 0){
    RET + = j的;
    }    返回RET;
}

I want to find the fastest way to get the index of the lowest order bit of a long long. ie:

00101001001000 -> 3

Solutions involving looping and shifting are too slow. ie:

int i;
if(bits == 0ULL) {
  i = 64;
} else {
  for(i = 0;!(bits & 1ULL);i++)
    bits >>= 1;
}

EDIT: Info on usage

The function that uses ffsll can't really reduce its usage, but here it is (simplified of course). It just iterates through the indices and does something with them. This function is perhaps the most widely used function in my whole application despite a lot of caching of its value. It's a legal move generator in my alpha-beta search engine.

while(bits){
  index = ffsll(bits);
  doSomething(index);
  index &= index-1;
}

解决方案

Intel has specialized instructions for finding either lowest or highest order set bit. BSF seems like what you need. as far as doing it in plain C, maybe the bit twiddling hacks page has what you need.

At the very least you could use a table of nibbles or bytes to speed things up. Something like this (demonstrated for int, but easily changeable to longlong as needed).

/*
0000 - 0
0001 - 1
0010 - 2
0011 - 1
0100 - 3
0101 - 1
0110 - 2
0111 - 1
1000 - 4
1001 - 1
1010 - 2
1011 - 1
1100 - 3
1101 - 1
1110 - 2
1111 - 1
*/

int ffs(int i) {
    int ret = 0;
    int j = 0;
    static const int _ffs_tab[] = 
    	{ 0, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1 };

    while((i != 0) && (ret == 0)) {
    	ret = _ffs_tab[i & 0x0f];

    	if(ret > 0) {
    		break;
    	}

    	i >>= 4;
    	j += 4;

    	/* technically the sign bit could stay, so we mask it out to be sure */
    	i &= INT_MAX;
    }

    if(ret != 0) {
    	ret += j;
    }

    return ret;
}

这篇关于最低阶位的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆