基本上
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
你已经介绍了如何做到这一点,所以我真的不明白你想要什么我们告诉你 – harold 2014-11-05 10:45:06
'&&'不是一个*位操作* – 2014-11-05 10:49:22
我希望有一些实现导向的建议,例如如何将给出的示例带入实际的代码示例 – KapaA 2014-11-05 10:50:58