基本上
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