Given the following C++ Code:
void Check(DWORD64 ptr)
{
if ( ! (ptr & 0x8000000000000000) )
return;
}
In C# this results in the following Error:
CS0023 Operator '!' cannot be applied to operand of type 'ulong'
How do I bitwise check the ptr parameter in C#?
Comparing to not 0?
void Check(ulong ptr)
{
if ((ptr & 0x8000000000000000) != 0)
return;
}
or checking for 0?
void Check(ulong ptr)
{
if ((ptr & 0x8000000000000000) == 0)
return;
}
Googleing for this questions leads to all sorts of answers on different bitwise operations but I couldn't find an answer for this specific negation with exclemation mark.
When operator ! "logical not" is applied to a numeric value in C or C++, it produces a result as follows:
1 if its operand is zero
0 otherwise
C's conditional statement if interprets 0 as "false" and any non-zero value, including 1, as "true". Therefore, your second option is correct.
The second one. C++ would treat any nonzero value as true, so the ! check on an integer was effectively equivalent to !(value != 0) or (value==0)
Related
How can I check if "1" is in "9" in C#?
long l1 = 1L; // 0001
long l9 = 9L; // 1001
if (l1 & l9) // True (Cannot implicit convert 'long' to 'bool)
{
}
It's possible with "&" in JavaScript and in vb it's "And", but I just can't figure out what I'm missing here.
// check if result of binary op is != 0
// that means "contains"
if ((l1 & l9) != 0)
{
...
}
You need to check if the result of the operation is not equal 0.
EDIT
As #Damien: correctly noted, in this case would correct to check against inequality to 0, as simple >0 comparison may produce false positives if 63th bit is somehow involved.
I need to perform a bitwise '&' operation on a value of type uint.
enum MsgType : ulong
{
Begin = 0x00000001,
}
unit number= 0x00000002;
if (number & MsgType.Begin == MsgType.Begin)
//Not working
It is giving an error:
Operator '&' cannot be applied on operands of type 'uint' or 'bool'
How to cast it?
it seems it is an issue of operator precedence in C#, use parentheses to produce the correct compiler output
i.e instead of this:
if (number & MsgType.Begin == MsgType.Begin)
do this:
if ((number & MsgType.Begin) == MsgType.Begin)
as per this related question
I am new to C# but not to programming. When I compare the lengths of two strings in the code below, I get the error:
Operator '&' cannot be applied to operands of type 'bool' and 'int'
Apparently string1.Length > 0 is seen as a boolean in this context.
How should I perform this comparison?
if (string1.Length > 0 & string2.Length = 0)
{
//Do Something
}
The reason for the error is because you have written = when you meant ==. In C#
string1.Length > 0 & string2.Length = 0
means
(string1.Length > 0) & (string2.Length = 0)
The type of the left side is bool and the type of the right side is int, which cannot be &-ed together, hence the error. Of course even if you managed to get past that, Length cannot be the target of an assignment either.
Use == to test for equality. = is assignment.
Consider also using && instead of &. The meaning of x & y is "evaluate both, the result is true if both are true and false otherwise". The meaning of x && y is "evaluate the left side; if it is false then the result is false so do not evaluate the right side. If the left side is true then proceed as & does."
When applied to integers, the & operator in C# is a bitwise AND, not a logical AND. Also = is an assignment, not an equality comparison operator. The string1.Length > 0 expression is indeed an expression of boolean type, while the assignment is integer (because 0 is integer).
What you need is
if (string1.Length > 0 && string2.Length == 0)
You probably meant to do this:
if (string1.Length > 0 && string2.Length == 0)
{
//Do Something
}
In C#, the = operator is just for assignment. The == is used for equality comparisons. You probably also want to use the && operator instead of & (&& will skip the second condition if the first condition evaluates to false).
However, if really want to 'compare the lengths of the strings', you can just do this:
if (string1.Length > string2.Length)
{
//Do Something
}
This will fix your problem.
if(string1.Length > 0 && string2.Length == 0)
I think you want a == for your equality test? C# assignment returns a value (as in C).
I am trying to understand the difference between & and &&operators in C#. I searched on the internet without success. Can somebody please explain with an example?
& is the bitwise AND operator. For operands of integer types, it'll calculate the bitwise-AND of the operands and the result will be an integer type. For boolean operands, it'll compute the logical-and of operands. && is the logical AND operator and doesn't work on integer types. For boolean types, where both of them can be applied, the difference is in the "short-circuiting" property of &&. If the first operand of && evaluates to false, the second is not evaluated at all. This is not the case for &:
bool f() {
Console.WriteLine("f called");
return false;
}
bool g() {
Console.WriteLine("g called");
return false;
}
static void Main() {
bool result = f() && g(); // prints "f called"
Console.WriteLine("------");
result = f() & g(); // prints "f called" and "g called"
}
|| is similar to && in this property; it'll only evaluate the second operand if the first evaluates to false.
Of course, user defined types can overload these operators making them do anything they want.
Strongly recommend this article from Dotnet Mob : http://codaffection.com/csharp-article/short-circuit-evaluation-in-c/
-&& is short-circuit logical operator
For AND operations if any of the operand evaluated to false then total expression evaluated to false, so there is no need to evaluate remaining expressions, similarly in OR operation if any of the operand evaluated to true then remaining evaluation can be skipped
-& operator can be used as either unary or binary operator. that is, unary & can be used to get address of it’s operand in unsafe context.
& can be used on either integral types (like int, long etc.) or on bool.
When used on an integral type, it performs a bitwise AND and gives you the result of that. When used on a bool, it performs a logical AND on BOTH its operands and gives you the result.
&& is not used as a bitwise AND. It is used as a logical AND, but it does not necessarily check both its operands. If the left operand evaluates to false, then it doesn't check the right operand.
Example where this matters:
void Action()
{
string name = null;
if(name != null && name.EndsWith("ack"))
{
SomeOtherAction();
}
}
If name is null, then name.EndsWith("ack") will never get executed. It is smart enough to know if the left operand is false, then the right operand doesn't need to be evaluated (aka "short-circuiting"). That's good because calling a method on null will throw a NullReferenceException.
If you changed it into if(name != null & name.EndsWith("ack")), both sides would get evaluated and it would throw a NullReferenceException.
One detail: & can also be a unary operator (so it has one operand) in an unsafe context. It will give the address of a value or object. It's not important though, as most people don't ever have to touch this part of the language.
Below example and explanation's may help.
Example:
public static bool Condition1()
{
Console.WriteLine("Condition1 is evaluated.");
return false;
}
public static bool Condition2()
{
Console.WriteLine("Condition2 is evaluated.");
return true;
}
1. Logical Operator
& (ampersand) Logical AND operator
| (pipeline) Logical OR operator
Used for ensuring all operands are evaluated.
if(Condition1() & Condition2())
{
Console.WriteLine("This will not print");
//because if any one operand evaluated to false ,
//thus total expression evaluated to false , but both are operand are evaluated.
}
if (Condition2() | Condition1())
{
Console.WriteLine("This will print");
//because any one operand evaluated to true ,
//thus total expression evaluated to true , but both are operand are evaluated.
}
2. Conditional Short Circuit Operator
&& (double ampersand) Conditional AND operator
|| (double pipeline) Conditional OR operator
Used for Skipping the right side operands , Has Side effects so use carefully
if (Condition1() && Condition2())
{
Console.WriteLine("This will not print");
//because if any one operand evaluated to false,
//thus total expression evaluated to false ,
//and here the side effect is that second operand is skipped
//because first operand evaluates to false.
}
if (Condition2() || Condition1())
{
Console.WriteLine("This will print");
//because any one operand evaluated to true
//thus remaining operand evaluations can be skipped.
}
Note:
To get better understanding test it in console sample.
References
dotnetmob.com
wikipedia.org
stackoverflow.com
& is a bitwise operator and && is a logical operator that applies to bool operands.
Easy way to look it is logical & will evaluate both sides of the & regardless if the left side is false, whereas the short-circuit && will only evaluate the right side if the left is true.
d=0;
n=10;
// this throws divide by 0 exception because it evaluates the
// mod even though "d != 0" is false
if ( (d != 0) & (n % d) == 0 )
Console.Writeline( d + " is a factor of " + n);
// This will not evaluate the mod.
if ( (d != 0) && (n % d) == 0 )
Console.Writeline( d + " is a factor of " + n);
The first one is bitwise and the second one is boolean and.
According to - C# 4.0 The Complete Reference by Herbert Schildt
& - Logical AND Operator
| - Logical OR Operator
&& - Short Circuited AND Operator
|| - Short Circuited OR Operator
A simple example can help understand the phenomena
using System;
class SCops {
static void Main() {
int n, d;
n = 10;
d = 2;
if(d != 0 && (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);
d = 0; // now, set d to zero
// Since d is zero, the second operand is not evaluated.
if(d != 0 && (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);
// Now, try the same thing without the short-circuit operator.
// This will cause a divide-by-zero error.
if(d != 0 & (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);
}
}
Here the & operator checks each and every operand and && checks only the first operand.
As you might notice for 'AND' operations any operand which is false will evaluate the whole expression to false irrespective of any other operands value in the expression.
This short circuited form helps evaluate the first part and is smart enough to know if the second part will be necessary.
Running the program will throw a divide-by-zero error for the last if condition where both the operands are checked for & operator and no exception handling is done to tackle the fact that 'd' can be 0 at any point of time.
The same case applies to '|' in C#.
This is slightly different than C or C++ where '&' and '|' were bitwise AND and OR operators. However C# also applies the bitwise nature of & and | for int variables only.
Hai Friend,
The Operator &&(Logical Operator) is used in conditional statements.
For Instance
if(firstName == 'Tilsan' && lastName == 'Fighter')
{
Response.Write("Welcome Tilsan The Fighter!");
}
the Response.Write statement will run only if both variables firstName and lastName match to their condition.
Whereas & (Bitwise Operator)operator is used for Binary AND operations, i.e., if we write:
bool a, b, c;
a = true;
b = false;
c = a & b;
Response.Write(c); // 'False' will be written to the web page
Here first Binary And operation will be performed on variables a and b, and the resultant value will be stored in variable c.
Newbie question.
How to calculate the value of the formula A f B, where f - the binary function OR or AND?
There is a distinction between the conditional operators && and || and the boolean operators & and |. Mainly it is a difference of precendence (which operators get evaluated first) and also the && and || are 'escaping'. This means that is a sequence such as...
cond1 && cond2 && cond3
If cond1 is false, neither cond2 or cond3 are evaluated as the code rightly assumes that no matter what their value, the expression cannot be true. Likewise...
cond1 || cond2 || cond3
If cond1 is true, neither cond2 or cond3 are evaluated as the expression must be true no matter what their value is.
The bitwise counterparts, & and | are not escaping.
Hope that helps.
Logical OR is ||, logical AND is &&.
If you need the negation NOT, prefix your expression with !.
Example:
X = (A && B) || C || !D;
Then X will be true when either A and B are true or if C is true or if D is not true (i.e. false).
If you wanted bit-wise AND/OR/NOT, you would use &, | and ~. But if you are dealing with boolean/truth values, you do not want to use those. They do not provide short-circuit evaluation for example due to the way a bitwise operation works.
if(A == "haha" && B == "hihi") {
//hahahihi?
}
if(A == "haha" || B != "hihi") {
//hahahihi!?
}
I'm not sure if this answers your question, but for example:
if (A || B)
{
Console.WriteLine("Or");
}
if (A && B)
{
Console.WriteLine("And");
}
Use '&&' for AND and use '||' for OR, for example:
bool A;
bool B;
bool resultOfAnd = A && B; // Returns the result of an AND
bool resultOfOr = A || B; // Returns the result of an OR
If what interests you is bitwise operations look here for a brief tutorial : http://weblogs.asp.net/alessandro/archive/2007/10/02/bitwise-operators-in-c-or-xor-and-amp-amp-not.aspx .bitwise operation perform the same operations like the ones exemplified above they just work with binary representation (the operation applies to each individual bit of the value)
If you want logical operation answers are already given.
&& it's operation return true only if both operand it's true which implies
bool and(bool b1, bool b2)]
{
if(b1==true)
{
if(b2==true)
return true;
}
return false;
}
|| it's operation return true if one or both operand it's true which implies
bool or(bool b1,bool b2)
{
if(b1==true)
return true;
if(b2==true)
return true;
return false;
}
if You write
y=45&&34//45 binary 101101, 35 binary 100010
in result you have
y=32// in binary 100000
Therefore, the which I wrote above is used with respect to every pair of bits
many answers above, i will try a different way:
if you are looking for bitwise operations use only one of the marks like:
3 & 1 //==1 - and
4 | 1 //==5 - or