There are two questions in your post: how to access an individual bit ? and how to select that bit ?
Concerning the first question, suppose you want to access the less significant bit (or, to make it simpler, the rightmmost bit), you can use a mask: suppose your data is b0011
for instance, you can mask with b0001
(i.e. 1
in decimal).
0 0 1 1
& 0 0 0 1
---------
0 0 0 1
The &
operator is the bitwise and
. If you look in your code sample, you have printf("%d:%d\n", b, (x&1));
in which you can see x & 1
, i.e. print the rightmost bit of x
.
Now comes the second question: how to put each bit in the rightmost position one after each other (said otherwise, how to select the bit to print) ? An easy solution is to shift
your data of 1
position to the right each time you want to select the next bit (i.e. the bit to the left of the current one).
In C, you can shift
using >>
. For instance, if x
is b0011
, then x >> 1
is b0001
(in this case, you fill the leftmost position with zeros, but in some cases it might be trickier). If you look in you code sample, you have x>>=1
in the for-loop
, which assigns x >> 1
in x
.
Hence, suppose you take the previous example:
0 0 1 1 = x 0 0 0 1 = x
& 0 0 0 1 & 0 0 0 1
--------- x >> 1 = b0001 -> x ---------
0 0 0 1 0 0 0 1
and so one...
A last bonus point, the loop stopping condition is x != 0
, this implies that you don't prints all bits of your data, but only the bits up to the leftmost 1
(included). For instance, in the above example, after printing the two rightmost bits, x
becomes 0
and the loop exits.