In C, C++, and similarly-syntaxed languages, you can determine if the right-most bit in an integer i
is 1 or 0 by examining whether i & 1
is nonzero or zero. (Note that that's a single &
signifying a bitwise AND operation, not a &&
signifying logical AND.) For the second-to-the-right bit, you check i & 2
; for the third you check i & 4
, and so on by powers of two.
More generally, to determine if the bit that's j
th from the right is zero, you can check whether i & (1 << (j-1)) != 0
. The <<
indicates a left-shift; 1 << (j-1)
is essentially equivalent to 2j-1.
Thus, for a 32-bit integer, your loop would look something like this:
unsigned int i = 26; /* Replace this with however it's actually defined. */
int j;
for (j = 31; j >= 0; j--)
{
if ((i & (1 << (j-1))) != 0)
/* do something for jth bit is 1 */
else
/* do something for jth bit is 0 */
}
Hopefully, that's enough to get you started.