Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 位扫描前向测试_C - Fatal编程技术网

C 位扫描前向测试

C 位扫描前向测试,c,C,我的函数应该在整数中查找LSB1的位索引 我的问题是,如何测试这是否有效?我猜该函数需要一个32位无符号整数,但所有的测试都失败了。我不知道是因为我的建筑还是什么 编辑: #include <stdio.h> #include <stdint.h> #include <assert.h> int bitscanforward(uint32_t v) { static const int MultiplyDeBruijnBitPosition[32] =

我的函数应该在整数中查找
LSB1
的位索引

我的问题是,如何测试这是否有效?我猜该函数需要一个32位无符号整数,但所有的测试都失败了。我不知道是因为我的建筑还是什么

编辑:

#include <stdio.h>
#include <stdint.h>
#include <assert.h>


int bitscanforward(uint32_t v) 
{

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
};
assert(v);
return MultiplyDeBruijnBitPosition[((v & -v) * 0x077CB531U) >> 27];

}


int main()

{

   uint32_t x = 0X05FEEEEE;
   int answer = bitscanforward(x);
   printf("Index of LS1B: ");
   printf( "%d", answer );

   return 0;

}
#包括
#包括
#包括
int位扫描前向(uint32\u t v)
{
静态常数int multipledBruijnbitPosition[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
};
断言(v);
返回多个bruijnbitposition[(v和-v)*0x077CB531U>>27];
}
int main()
{
uint32_t x=0x05英尺;
int answer=位扫描前向(x);
printf(“LS1B索引:”);
printf(“%d”,答案);
返回0;
}

使用
typedef
您自己的
unit32
是不好的做法:请注意,您的版本将不起作用,因为
long
至少是64位)。使用标准定义的
stdint.h
。在那里,您将(很可能)找到
uint32\u t
,它保证可以保存32位

为了验证您的代码,您可以使用unittest框架,或者只使用经过深思熟虑的参数调用函数并检查结果(框架的作用基本相同)


请注意,函数的名称应该表示它的实际功能。你的没有。对于给定的任务,通常使用“查找第一个”/ffo。一些编译器(如gcc)已经为此内置了函数(直接映射到某些CPU上的汇编指令)。

如果可以称为“查找第一个”,那么也可以称为BitScanForward谢谢,你能给我一个我该怎么称呼它的例子吗?对不起,long应该是long,当然是long,我编辑了它。
long
也不能保证32位。对于内部整数类型,只保证最小范围,而不是最大范围(只是排序)。使用标准方式而不是自制方式有什么问题?对于内置,只需参考-选择您的版本,“C语言扩展”。你们测试了什么?发生了什么?我测试的结果是0。你们知道常数是八进制吗?在任何情况下它都是奇怪的,所以它应该产生零结果。一个正确的测试包括所有有问题的模式。我仍然没有得到正确的结果,我只是编辑了我的原始帖子。