16,472
社区成员
发帖
与我相关
我的任务
分享
// 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;
}
int a = 1234; //10011010010
int lBitPos, hBitPos;
__asm
{
bsr eax, dword ptr[a]
mov hBitPos, eax //高位1,从右至左数在10位(0,1,2...10)
bsf eax, dword ptr[a]
mov lBitPos, eax //低位1,从右至左数在2位(0,1)
}