简体   繁体   中英

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?

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.

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.

A single ampersand is usually a bit-wise operation, but the exclamation is a logical operation. You need to use two ampersands a la C++ if you want a logical AND:

curStyle = curStyle && (!ES_NUMBER); 

Or a tilde if you want a bit-wise AND:

curStyle = curStyle & (~ES_NUMBER);

The key question is (and the answer to which is not provided): Is curStyle an integer or a bool? Are you trying to get a truth value (bool, true/false), or are you trying to mask out bits in a bit field?

For the former case, where curStyle is a bool (truth value), you say:

curStyle = curStyle && !ES_NUMBER ;

The latter case, where curStyle is an integer type and you want to manipulate its bits, takes:

curStyle = curStyle & ~Not ES_NUMBER ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM