gpt4 book ai didi

c - 发生事件时向左移位一次

转载 作者:太空宇宙 更新时间:2023-11-04 08:34:43 25 4
gpt4 key购买 nike

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

例如:

  • 在时间段 0,有一个事件:set mem_holder = 001
  • 在时间段 1,另一个事件:将 mem_holder 移位 1 和新事件 -> 011
  • 在时间段 2,没有事件,所以我们将两个位都向左移动一位 -> 110
  • 在时间段 3,没有事件再次向左移动 -> 100
  • 在时间段 4,新事件 -> 001
  • 在时间段 5,没有事件 -> 010
  • 在时间段 6,新事件 -> 101

等等等等

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

我对位运算知之甚少,但我知道一些基础知识,例如<< | >> & ^ 但是将它们组合在“大”环境中是具有挑战性的,因此我们不胜感激任何建议/帮助!

高级的谢谢

最佳答案

基本上,您有一个 3 位整数,这意味着它可以保存从 b000 到 b111 的值,即 0 到 7。如果您与任何包含 7 的整数进行 AND 运算,除了最右边的 3 位之外,您将清除所有内容。

那么,您要做的是左移 1 位来为新位腾出空间,然后按位 - 并使用 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

关于c - 发生事件时向左移位一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26755187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com