I've found this in code, but I never encountered such thing as &
, only &&
if ((code & 1) == 1){
Can you tell me what is it?
I've found this in code, but I never encountered such thing as &
, only &&
if ((code & 1) == 1){
Can you tell me what is it?
This is bitwise operator. This means that some action is done with 'code' before comparasion happens. Wikipedia says:
A bitwise AND takes two equal-length binary representations and performs the logical AND operation on each pair of the corresponding bits, by multiplying them. Thus, if both bits in the compared position are 1, the bit in the resulting binary representation is 1 (1 × 1 = 1); otherwise, the result is 0 (1 × 0 = 0 and 0 × 0 = 0).
By the way, there is such thread but about C++ not C, here.
It's a bitwise and operator.
It checks that the first bit of code
is 1, so it checks the code
is odd.
&
is binary AND operator copies a bit to the result if it exists in both operands.
For example:
(A & B) = 12, i.e., 0000 1100
It's the bitwise and operator:
/* binary: 0100, 0010 and 0111*/
int x = 4, y = 2, z = 7;
/* then: */
printf("x & y = %d\n", x&y);
printf("x & z = %d\n", x&z);
printf("y & z = %d\n", y&z);
Output:
x & y = 0 x & z = 4 y & z = 2
You have the same for the or operation:
/* then: */
printf("x | y = %d\n", x&y);
printf("x | z = %d\n", x&z);
printf("y | z = %d\n", y&z);
Output:
x | y = 6
x | z = 7
y | z = 7
So in your case, the if ((code & 1) == 1)
is a test to know if less significant bit is raised in code