VC中實現GCC的2個比較經常使用的位運算函數

在GCC中內嵌了兩個位運算的函數,但在VC中並無這兩個函數(有類似函數)。app

//返回前導的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)從左向右掃描,即:從高位向低位掃描。

處理方法

下面簡單實現這兩個函數。把這兩個測試代碼貼出來供遇到一樣問題的人提幫助。ui

輸出的值和GCC版本是一致的,可直接使用。spa

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提供幫助code

相關文章
相關標籤/搜索