简体   繁体   中英

C# bitwise negation ! check equivalent

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.

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)

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 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