/* Print binary equivalent of characters using showbits( ) function */
#include <stdio.h>
void showbits(unsigned char);
int main() {
unsigned char num;
for (num = 0; num <= 5; num++) {
printf("\nDecimal %d is same as binary ", num);
showbits(num);
}
return 0;
}
void showbits(unsigned char n) {
int i;
unsigned char j, k, andmask;
for (i = 7; i >= 0; i--) {
j = i;
andmask = 1 << j;
k = n & andmask;
k == 0 ? printf("0") : printf("1");
}
}
Sample numbers assigned for num : 0,1,2,3,4 ...
Can someone explain in detail what is going on in
k = n & andmask? How can n, which is a number such as 2, be an operand of the same & operator with andmask, eg 10000000, since 2 is a 1-digit value and 10000000 is a multiple-digit value?
Also why is char is used for n and not int?
Let's walk through it.
Assume
nis2. The binary representation of2is00000010.The first time through the loop
jis equal to7. The statementtakes the binary representation of
1, which is00000001, and shifts it left seven places, giving us10000000, assigning toandmask.The statement
performs a bitwise AND operation on
nandandmask:and assigns the result to
k. Then ifkis0it prints a "0", otherwise it prints a "1".So, each time through the loop, it's basically doing
Thus, the output is "00000010".
So the
showbitsfunction is printing out the binary representation of its input value. They're usingunsigned charinstead ofintto keep the output easy to read (8 bits instead of 16 or 32).Some issues with this code:
unsigned charis always 8 bits wide; while this is usually the case, it can be (and historically has been) wider than this. To be safe, it should be using theCHAR_BITmacro defined inlimits.h:?:is not a control structure and should not be used to replace anif-else- that would be more properly written as That tellsprintfto output a'1'ifkis non-zero,'0'otherwise.