如何按特定顺序设置位域,并在以后根据顺序进行检查



假设我在一个系统中有 3 个可以调用或不调用的函数。 稍后在我的算法中(参见下面的">myMainFunction((">(,我很想知道是否调用了所有函数。

实际上,为了跟踪我的函数是否被调用,我使用了一个辅助函数来设置一个 16 位字段:

static void SetBitField(u16 p_Bitfield, u8 Bit)
{
u16 tmp_Bitmask;
tmp_Bitmask = (u16)((u16)(1) << (u16)(Bit));
*p_Bitfield |= tmp_Bitmask;
}

现在在我的函数中,我正在执行以下操作:

static u16 BitMask;
#define SHIFT_0     0
#define SHIFT_1     1
#define SHIFT_2     2
#define MASK        7
fun1()
{
/*doing some stuff*/
SetBitField(&BitMask,SHIFT_0)
}
fun2()
{
/*doing some stuff*/
SetBitField(&BitMask,SHIFT_1)
}
fun3()
{
/*doing some stuff*/
SetBitField(&BitMask,SHIFT_2)
}

现在在主函数中,我可以检查是否调用了所有函数

myMainFunction()
{
/*doing some stuff*/
if ((BitMask & MASK) == MASK)
{
/*all functions are called*/
}
/*doing some stuff*/
}

到目前为止,这很好。但是最后,无论以哪种顺序调用函数,我都会得到相同的BitMask。 但是如何修改 SetBitField(( 函数,以便我稍后可以检查我的函数是否按特定顺序调用。 例如,检查 func1(

( --> func2(( --> func3(( 被调用,而不是例如 func2(( --> func1(( --> func3((?知道吗?

"你无法通过查看轨道来知道火车的路线",也无法通过查看位来知道函数的调用顺序。他们只会告诉你该函数被调用,但不会以哪个顺序调用。

但是,以下内容确实如此:

struct BITMASK {
unsigned int b1:3;
unsigned int b2:3;
unsigned int b3:3;
unsigned int b4:3;
unsigned int b5:3;
unsigned int b6:3;
unsigned int b7:3;
} myBits;
int counter;
static void SetBitField(u8 Bit)
{
switch (Bit) {
case 0: myBits.b1= ++counter; return;
case 1: myBits.b2= ++counter; return;
case 2: myBits.b3= ++counter; return;
case 3: myBits.b4= ++counter; return;
case 4: myBits.b5= ++counter; return;
case 5: myBits.b6= ++counter; return;
case 6: myBits.b7= ++counter; return;
}
}

所以这里你使用三个位(最多七个函数调用(来保存一个数字,这是调用的顺序。

给定 3 个函数和移位值 (1, 2, 3(。

如果在函数调用时应用此规则:

  • 设置最高有效位,然后按相应的值向右移动。

对于给定的(订单(,您将获得[这些位]:

(1, 2, 3) [0, 0, 0, 1, 0, 1, 1, 0]
(1, 3, 2) [0, 0, 1, 0, 0, 1, 1, 0]
(2, 1, 3) [0, 0, 0, 1, 1, 0, 1, 0]
(2, 3, 1) [0, 1, 0, 0, 1, 0, 1, 0]
(3, 1, 2) [0, 0, 1, 1, 0, 0, 1, 0]
(3, 2, 1) [0, 1, 0, 1, 0, 0, 1, 0]

生成位的 python 脚本用于示例目的:

import itertools                             
def mark(v, x):                              
v[0] = 1                                   
v = [0] * x + v[:-x]                       
return v                                   
for x in itertools.permutations([1,2,3]):    
v = [0] * 8                                
for xx in x:                               
v = mark(v, xx)                          
print x, v                                 

相关内容

最新更新