For a long time, the difference between logic and (&) is not very definite. I went online today and wroteCodeThe differences are as follows for discussion.
- When all operands are numbers
A. after bitwise AND (&) are performed on two numbers, the two numbers are converted to binary values, and then right-aligned (the digits are not filled with zeros, for example, the binary representation of 11 & 11 is, And the binary representation of 3 is 11. After right alignment and operation ,:
The result is 3.
B. for the logic and (&) of the two numbers, both operands are converted to the Boolean logical value (if the value is not 0, the value is true; otherwise, the value is false ), and then proceed with the operation.
The Demo code is as follows:
Static void main ()
{
Int I = 11; // The binary is: 1011
Int J = 3; // The binary value is: 0011.
Int num = I & J;
Int num1 = convert. toint32 (convert. toboolean (I) & convert. toboolean (j ));
Console. writeline ("bitwise AND result: {0}", num );
Console. writeline ("logic and Result: {0}", num1 );
}
2. the operand is not a number. It is the equation or method that returns the logical value.
A. For bitwise AND (&), all operands are judged. Let's take a look at the Demo code:
Static void main ()
{
If (3 = 5 & returntrue ())
{
Console. writeline ("the result is true ");
}
}
Static bool returntrue ()
{
Console. writeline ("executing the returntrue method ");
Return true;
}
The output result is:Execute the returntrue Method
The analysis is as follows:Equation 3 = 5 returns false results. We know from the output results that the returntrue () method is still executed when Equation 3 = 5 returns false, output result "execute returntrue method"
B. For logic and (&), the operands are determined one by one. When they do not match, the subsequent operands are no longer judged. Let's take a look at the Demo code:
Static void main ()
{
If (3 = 5 & returntrue ())
{
Console. writeline ("the result is true ");
}
}
Static bool returntrue ()
{
Console. writeline ("executing the returntrue method ");
Return true;
}
This Code does not output any results.
The analysis is as follows:Equation 3 = 5 returns false results. We know from the output results that the returntrue () method is not executed when Equation 3 = 5 returns false.
The result is:3.