一个事件向左移位一次



我正在研究一个需要增加计数器的问题。此计数器的工作方式类似于大小为3的事件内存保持器。这意味着您可以存储过去三个时间段内发生的事件。

例如:

  • 在时隙0,出现了一个事件:set mem_holder=001
  • 在时隙1,另一个事件:用1和shift mem_holder以及新事件->011
  • 在时隙2,没有事件,所以我们将两个比特都左移一个->110
  • 在时隙3,没有事件再次向左移动->100
  • 在时隙4,新事件->001
  • 在时隙5,无事件->010
  • 在时隙6,新事件->101

等等

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

我对bit操作知之甚少,但我知道一些基本知识,例如<lt;|>>&^但是,在"大"的环境中结合它们是具有挑战性的,所以任何建议/帮助都是值得赞赏的!

高级中的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        

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

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

最新更新