Reputation: 254
I have been looking at an example piece of code for a binary counter, I am having difficulty fully understanding what is taking place within the for loop switching each of the ledOnOffState using the bitwise operation.
It is the (i & 1), (i & 2), and (i & 4) that I'm having a little trouble with at the moment, for each of the i numbers counting from 0 - 7.
I think what is happening is for each of the i decimals within the loop their binary values are being used for the operation against the binary values for the 1, 2, and 4 in the () for the ledOnOffState. But I not quite sure exactly what these parts are doing. For instance when i = 3, 011, what is happening for each of the (3 & 1), (3 & 2) and (3 & 4), to produce 1, 1, and 0 respectively for binary value of 011?
bool led1OnOffState; // true = 1 = ON (HIGH), false = 0 = OFF (LOW)
bool led2OnOffState;
bool led3OnOffState;
int iterations = 2;
for (int iteration = 0; iteration < iterations; iteration++)
{
// a for loop that counts from 0 to 7
for (int i = 0; i < 8; i++)
{
// check to see if the 1, 2, and 4 bits are set for the current counter number
led1OnOffState = (i & 1); // check for binary bit value 1 = true (1) or false (0)
led2OnOffState = (i & 2); // check for binary bit value 2
led3OnOffState = (i & 4); // check for binary bit value 4
printf("The decimal %d is %d%d%d in binary\n", i, led3OnOffState, led2OnOffState, led1OnOffState);
If it is only comparing one bit for instance the 2^0 bits for the (3 & 1) and the 2^1 bits for the (3 & 2) and the 2^2 bits for the (3 & 4) in these cases it would makes sense to me, as it results in 1, 1, 0 respectively.
But I suspect that is not quite the case, my other thought is that perhaps it is performing 3 bitwise AND operations on each of the bits and if any of them are true it changes the ledOnOffState value to TRUE if none are true it is changed to FALSE.
I tried the code using a ledOnOffState = (i & 3) and the results led me to think the latter case may be true, as only the 0 and 4 decimal values were 0 but all other came up as 1s.
Upvotes: 0
Views: 69
Reputation: 214525
Any non-zero integer assigned to a bool
gets implicitly converted to 1
/true
, otherwise 0
/false
. The masks 1, 2 and 4 respectively simply refers to the 3 least significant bits of the value, binary 001
, 010
, 100
. If the masked bit is set, each expression will evaluate to true
.
This means that this code generates a truth table according to this:
i LED1 LED2 LED3
0 0 0 0
1 1 0 0
2 0 1 0
3 1 1 0
4 0 0 1
...
That is, the code is simply doing a binary count-up and spreading it across 3 bool variables.
A more conventional approach, as done in real-world embedded systems, is to route all 3 LEDs to the same port using pin 0,1,2, then simply do this:
for (int i = 0; i < 8; i++)
{
PORT = i;
}
Upvotes: 2