代码之家  ›  专栏  ›  技术社区  ›  JohnDoe

如何在特定顺序中设置位字段,并在以后对照顺序进行检查

c
  •  0
  • JohnDoe  · 技术社区  · 6 年前

    稍后在我的算法中(参见“ myMainFunction()

    实际上,为了跟踪是否调用了我的函数,我使用了设置16位字段的helper函数:

    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*/
    }
    

    到目前为止还不错。但最后,不管函数的调用顺序如何,我都会得到相同的位掩码。 但是如何修改SetBitField()函数,以便以后检查函数是否按特定顺序调用。

    知道吗?

    2 回复  |  直到 6 年前
        1
  •  0
  •   Paul Ogilvie    6 年前

    “你不能通过观察铁轨来知道火车是怎么走的”,也不能通过观察这些位来知道这些函数是按什么顺序调用的。它们只会告诉您调用了该函数,但不会按顺序调用。

    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;
        }
    }
    

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

        2
  •  0
  •   perreal    6 年前

    给定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