Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting bitwise AND/NOT from VB.NET to C#

Original code (VB.NET):

curStyle = curStyle And (Not ES_NUMBER)

Changed code (C#):

curStyle = curStyle & (!ES_NUMBER);

But it is giving me this error:

Operator '!' cannot be applied to operand of type 'long'

ES_NUMBER is of data type long. I tried changing it to int, string, etc. All doesn't work.

How do I solve this problem?

like image 742
Soe Htike Avatar asked Jul 21 '11 16:07

Soe Htike


2 Answers

And is the same as &; you got that correctly. Not in front of a Long is a bitwise NOT operator. The C# equivalent is ~.

The C# code would be:

curStyle = curStyle & (­~ES_NUMBER);

Check out Bitwise operators in c# OR(|), XOR(^), AND(&), NOT(~) , explaining C# bitwise operators.

like image 153
Meta-Knight Avatar answered Sep 24 '22 23:09

Meta-Knight


Once again, a trip to the documentation proves instructional:

From MSDN:

The logical negation operator (!) ... is defined for bool and returns true if and only if its operand is false.

There is nothing in the documentation anywhere about any behavior at all for numeric expressions, which I would expect mean that the operator is not defined to work with those expressions at all.

On the other hand, MSDN has this to say about VB.NET's Not operator:

For numeric expressions, the Not operator inverts the bit values of any numeric expression and sets the corresponding bit in result according to the following table...

So the question is now: How to reproduce the behavior of VB.NET's "Not" for C#? Thankfully, it's not hard: you can use the ~ operator.

curStyle = curStyle & (­~ES_NUMBER);

And, just for good measure, the documentation on &:

For integral types, & computes the bitwise AND of its operands.

like image 32
Joel Coehoorn Avatar answered Sep 25 '22 23:09

Joel Coehoorn