algorithm - Checking if a bit is set using the AND operator -


in few code examples, i've seen algorithms check if bit set such in following:

for (int = 0; < 32; i++)     {         // count number of elements i'th bit set         int count = 0;         (int j = 0; j < n; j++)             if ( (arr[j] & (1 << i)) ) // array holds integers                 count++; 

where if statement checks see if current number in array has ith bit turned on. example, if number in current index of array 4 (0100 in 4-bit representation) , 2 (corresponding 3rd bit), , operation be

0100 0100 & = 0100 

which returns 4. since if statements check truth values (values of 1 or 0) how interpret , operation true cases 1 described?

if example compiles, doing in c, c++, or objective-c (as opposed java or c#, example wouldn't compile).

both c , c++ have rule interprets zeros false , all non-zeros true in contexts logical expression expected. imagine implicit != 0 appended numeric expressions in contexts logical expression expected.

if statement requires logical expression, non-zero value considered true. why implementation works.


Comments