2014-11-05 50 views
0

我正在查看需要增加计数器的问题。此计数器的作用类似于大小为3的事件存储器。这意味着您可以存储最近三个时间段内发生的事件。在事件发生时移位一次

例如:

  • 在时隙0,有一个事件:设置mem_holder = 001
  • 在时隙1中,另一事件:用1移mem_holder和和新的事件 - > 011
  • 在时隙2中,任何情况下,所以我们两个位与一个左移 - > 110
  • 在时隙3,无事件再次转移既左 - > 100
  • 在时隙4中,新的事件 - > 001
  • 在时隙5,任何情况下 - > 010
  • 在时隙6,新的事件 - > 101

等等等等

我所寻找的是一个提示或一个如何以适当和有效的方式解决这个问题的例子。 该标准是低复杂度和低内存要求,即没有大的变量分配。

我对位操作知之甚少,但是我知道基础知识,例如< < | >> & ^但在“大”的背景下将它们结合在一起是具有挑战性的,所以任何建议/帮助都是值得赞赏的!在先进

+1

你已经介绍了如何做到这一点,所以我真的不明白你想要什么我们告诉你 – harold 2014-11-05 10:45:06

+2

'&&'不是一个*位操作* – 2014-11-05 10:49:22

+0

我希望有一些实现导向的建议,例如如何将给出的示例带入实际的代码示例 – KapaA 2014-11-05 10:50:58

回答

2

基本上

THX,你有3位整数,这意味着它可以从B000举办值B111,所以0〜7如果你和任何整数7,你清楚了什么但最右边的3位。

所以,你做了什么,是你左移一位为新位置,然后按位置 - 和7.最新的最右边的位现在为0,因为你的左移。在此之后,如果有新事件,则使用按位或 - 将最右边的位设置为1。

#include <stdio.h> 

void mark(int new_event) { 
    static int bits = 0; 

    /* Shift the bits one left to make place for the new event bit. 
    * Make sure only 3 bits are used. */ 
    bits <<= 1; 
    bits &= 7;   /* 7 is in binary 111, all other bits get removed */ 

    /* Put in the rightmost bit a 1 if new_event is 'true', else it's 
    * already zeroed-out due to the above leftshift */ 
    if (new_event) 
     bits |= 1; 
    /* Note: if you're sure that new_event can only have values 0 and 1, then 
    * you can do an unconditional: 
    * bits |= new_event 
    */ 

    /* Output what we've done for demo purposes */ 
    printf("New event: %d. Bits: ", new_event); 
    putchar(bits & 4 ? '1' : '0'); 
    putchar(bits & 2 ? '1' : '0'); 
    putchar(bits & 1 ? '1' : '0'); 
    putchar('\n'); 
} 

int main() { 
    /* at time slot 0, there was a event: set mem_holder = 001 
     at time slot 1, another event: shift mem_holder with 1 
         and and the new event -> 011 
     at time slot 2, no event so we shift both bits with one to left -> 110 
     at time slot 3, no event shift both again to left -> 100 
     at time slot 4, new event -> 001 
     at time slot 5, no event -> 010 
     at time slot 6, new event -> 101 
    */ 
    mark(1); 
    mark(1); 
    mark(0); 
    mark(0); 
    mark(1); 
    mark(0); 
    mark(1); 

    return 0; 
} 

输出:

New event: 1. Bits: 001 
New event: 1. Bits: 011 
New event: 0. Bits: 110 
New event: 0. Bits: 100 
New event: 1. Bits: 001 
New event: 0. Bits: 010 
New event: 1. Bits: 101   
0

另外,您可以使用一个不那么复杂的逻辑:

mem_holder = (mem_holder*2)%8 + event 
where event can take values [0,1]. 
+0

好吧,它并不比mem_holder =((mem_holder << 1)&7)|更复杂。事件,对吧? – 2014-11-05 22:00:27

+0

这里的所有操作都比比特等价的更复杂,并且仅仅是等价的,因为它们是碰巧很简单的特殊情况。 – harold 2014-11-06 08:47:19

相关问题