【发布时间】:2016-07-11 15:01:54
【问题描述】:
我有一个由九个元素和一个整数组成的数组。 使用整数和位掩码,我想保存有关数组元素是否有效的信息。
所以我的问题是:有没有比使用 math.h 的 log2() 从我的位掩码获取数组元素编号更简单的方法?
例如,我使用位掩码将foo2, foo4 和foo5 存储在mValue 中。
然后我想得到位置foo2 = 2的数组元素,也就是第二位,所以第二个数组元素,就是34。
但我能想到的唯一方法是log2(n) 功能。
有没有更简单的使用位移的方法?
简单地说,我想这样做:
整数mValue的第n位是否设置为1?然后给我数组bar的第n个元素。
#include <math.h>
const int foo1 = 1;
const int foo2 = 2;
const int foo3 = 4;
const int foo4 = 8;
const int foo5 = 16;
int bar[9] = {23,34,82,8,7,0,23,19,20};
int mValue;
void SetValue(int nVal)
{
mValue = nVal;
}
bool IsElementValid(int nVal)
{
return mValue & nVal;
}
int main()
{
SetValue(foo2 | foo4 | foo5 );
IsElementValid(foo4); //true
IsElementValid(foo5); //true
IsElementValid(foo1); //false
//access array element 1 with value foo2 (2)
if(IsElementValid(foo2))
printf("%d\n", bar[log2(foo2)]); // output: '34'
}
【问题讨论】:
-
this question and answers 可能对你有用
标签: c bit-manipulation bit-shift bitmask