问题
I'm still new with programming and I'd like to ask about one specific question about the C
language. I'm using codeblocks compiler.
Here is a piece of code:
int n, c, k;
scanf("%d",&n);
for(c = 31;c >= 0;c--)
{
k = n >> c;
if(k & 1)
printf("1");
else
printf("0");
}
return 0;
that I got from one website and it converts the base to the binary one.
My question is, where I have an if&else statement, why is there if(k & 1) printf("1") ?? I thought that k can be both 1 and 0 and if I use (k & 1) there are two options such as (0 & 1) = 0 and (1 & 1) = 1. Can please anybody explain me this? Thank you very much.
回答1:
The expression inside of an if statement always evaluates to true or false. In terms of integers, 0 means false, and anything non-zero means true. When you have k & 1
, that means that if the least-significant bit of k
is 1, then that expression evaluates to 1 and is therefore considered true. If the least-significant bit of k
is 0, then the expression evaluates to 0 and is therefore considered to be false.
回答2:
One thing that helped me when I was starting was to 'manually' run through the code a few times with pen-and-paper.
To give you an example, lets consider your loop (but work with 8-bit integers rather than 32-bit integers):
for(c = 7; c >= 0; c--)
{
k = n >> c;
if(k & 1)
printf("1");
else
printf("0");
}
I am assuming the other code in your example doesn't change. Furthermore, assume that the user entered 218 (or 11011010 in binary).
first iteration:
n is 218, c is 7.
we do a right shift 7 (n >> c) which makes k 00000001
we do a bit-wise `and' of k and 1 (K & 1), which is 1 or true
we print "1"
second iteration:
n is 218, c is 6.
we do a right shift 6 (n >> c) which makes k 00000011
we do a bit-wise `and' of k and 1 (k & 1), which is 1 or true
we print "1"
third iteration:
n is 218, c is 5.
we do a right shift 5 (n >> c) which makes k = 00000110
we do a bit-wise `and' of k and 1 (k&1), which is 0 or false
we print "0"
and so on...
So, you are correct that k can be either 0 or 1, however it assumes only one of those values each time through the loop.
Finally, in case you are unclear on how the bit-wise `and' works, it looks at the n-th bit in both numbers and if they are the same it sets the n-th bit of the result to one (1) otherwise it sets the result to zero (0). Consider the bit-wise and of 218 with 15:
218 is 11011010 e.g. third bit from right is zero
15 is 00001111 e.g. third bit from right is one
-----------------
& 00001010 e.g. third bit from right is zero
来源:https://stackoverflow.com/questions/24586632/convert-base-10-to-base-2-c-programming