設置的最低有效位的位置
Position of least significant bit that is set(設置的最低有效位的位置)
本文介紹了設置的最低有效位的位置的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在尋找一種有效的方法來確定設置在整數中的最低有效位的位置,例如對于 0x0FF0,它將是 4.
一個簡單的實現是這樣的:
unsigned GetLowestBitPos(無符號值){斷言(值!= 0);//單獨處理無符號位置 = 0;while (!(value & 1)){值>>=1;++位置;}返回位置;}
任何想法如何從中擠出一些周期?
(注意:這個問題是針對喜歡這種東西的人,而不是告訴我xyz優化是邪惡的.)
[edit] 感謝大家的想法!我也學到了一些其他的東西.酷!
解決方案
Bit Twiddling Hacks
a> 提供了一個很好的集合,呃,一些小技巧,并附有性能/優化討論.對于您的問題(來自該站點),我最喜歡的解決方案是乘法和查找":
unsigned int v;//在 32 位 v 中找到尾隨零的數量國際r;//結果在這里static const int MultiplyDeBruijnBitPosition[32] ={0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9};r = MultiplyDeBruijnBitPosition[((uint32_t)((v & -v) * 0x077CB531U)) >>27];
有用的參考資料:
- "使用 de Bruijn 序列索引計算機單詞中的 1"- 解釋上述代碼為何有效.
- "董事會代表 >位板 >比特掃描"- 對該問題的詳細分析,特別關注國際象棋編程
I am looking for an efficient way to determine the position of the least significant bit that is set in an integer, e.g. for 0x0FF0 it would be 4.
A trivial implementation is this:
unsigned GetLowestBitPos(unsigned value)
{
assert(value != 0); // handled separately
unsigned pos = 0;
while (!(value & 1))
{
value >>= 1;
++pos;
}
return pos;
}
Any ideas how to squeeze some cycles out of it?
(Note: this question is for people that enjoy such things, not for people to tell me xyzoptimization is evil.)
[edit] Thanks everyone for the ideas! I've learnt a few other things, too. Cool!
解決方案
Bit Twiddling Hacks offers an excellent collection of, er, bit twiddling hacks, with performance/optimisation discussion attached. My favourite solution for your problem (from that site) is ?multiply and lookup?:
unsigned int v; // find the number of trailing zeros in 32-bit v
int r; // result goes here
static const int MultiplyDeBruijnBitPosition[32] =
{
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
r = MultiplyDeBruijnBitPosition[((uint32_t)((v & -v) * 0x077CB531U)) >> 27];
Helpful references:
- "Using de Bruijn Sequences to Index a 1 in a Computer Word" - Explanation about why the above code works.
- "Board Representation > Bitboards > BitScan" - Detailed analysis of this problem, with a particular focus on chess programming
這篇關于設置的最低有效位的位置的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!