The statement:
if (counter & (1<<j))
checks if the j
-th bit of counter
is set. In more detail, 1 << j
uses shifting of 1
to generate a bit mask in which only the j
-th bit is set. The &
operator then masks out the j
-bit of counter
; if the result is not zero (which means that the j
-th bit of counter
was set), the condition is satisfied.
Consider the following example. If counter
is 320, its binary representation is 101000000
, which means that the 6th bit (the one corresponding to the value of 64) is set; let's test for that bit. The bit mask is generated by shifting 1
, which has the binary representation 000000001
, 6 places to the right, which results in the binary value 001000000
. The value of counter
, namely:
101000000
is combined with &
, which is the bitwise and-operator, with the bit mask as follows:
101000000
& 001000000
---------
001000000
The value 001000000
again corresponds to the value of 64; however this is not important here, it only matters that it is not zero (as it has a nonzero bit, namely the bit for which we intended to check). In total, the condition
if ( 64 )
is satisfied. In the semantics of C (which does not feature a native Boolean data type) any nonzero value is treated as true when checked with if
.
<<
means that the left-hand operand is multiplied by 2, for as many times as the number in the right-hand operand. E.g.1 << 3
means1*2*2*2
. – Endoparasitecounter & (stuff)
results in a bitwiseAND
ofcounter
andstuff
– Maurreen