在GCC中內嵌了兩個位運算的函數,但在VC中並沒有這兩個函數(有相似函數)。
//返回前導的0的個數。
int __builtin_clz (unsigned int x)
//返回后面的0個個數,和__builtin_clz相對。
int __builtin_ctz (unsigned int x)
這兩個函數在radix tree中直接計算索引,對性能有一定要求。
自己寫有些效率問題不是很理想,所以想確定vc2015 版本中是否有帶已經優化過的函數。
在網上兜了一圈,沒有找到類似VC實現的代碼。折騰了半天沒找到解決方案,后來到CSDN上發了個貼解決問題。
VC相似函數
_BitScanForward()
[ref]: https://msdn.microsoft.com/en-us/library/wfd9z0bb.aspx
_BitScanReverse()
[ref]: https://msdn.microsoft.com/en-us/library/fbxyd7zd.aspx
有64位版本的處理,需要處理一下就和GCC中得到相同結果
基本原理
- 正向掃描指令BSF(BitScan Forward)從右向左掃描,即:從低位向高位掃描;
- 逆向掃描指令BSR(BitScan Reverse)從左向右掃描,即:從高位向低位掃描。
處理方法
下面簡單實現這兩個函數。把這兩個測試代碼貼出來供遇到同樣問題的人提幫助。
輸出的值和GCC版本是一致的,可直接使用。
vc test code(32位)
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <bitset>
using namespace std;
__inline int __builtin_clz(int v)
{
if (v == 0)
return 31;
__asm
{
bsr ecx, dword ptr[v];
mov eax, 1Fh;
sub eax, ecx;
}
}
__inline int __builtin_ctz(int v)
{
int pos;
if (v == 0)
return 0;
__asm
{
bsf eax, dword ptr[v];
}
}
int main()
{
// clz
printf("__builtin_clz:\n");
for (int i = 0; i < 32; i++) {
int v = 1 << i;
bitset<32> b(v);
printf("%12u(%s): %2d %s \n", v, b.to_string().c_str(), __builtin_clz(v), __builtin_clz(v) == 31 - i ? "OK" : "Err");
}
printf("\n");
// ctz
printf("__builtin_ctz:\n");
for (int i = 0; i < 32; i++) {
int v = 1 << i;
bitset<32> b(v);
printf("%12u(%s): %2d %s \n", v, b.to_string().c_str(), __builtin_ctz(v), __builtin_ctz(v) == i ? "OK" : "Err");
}
return 0;
}
感謝CSND論壇的zwfgdlc提供幫助
