How to use the & operator in C#? Is the the translation of the code correct?

前端 未结 3 369
时光说笑
时光说笑 2021-01-20 15:31

the line \"if(arg2 & 1)\" in C++(arg2 is DWORD) is equal to \"if(arg2 & 1==0)\" in C#(arg2 is Uint32),right?

I am trying to translate a function from C++ to

相关标签:
3条回答
  • 2021-01-20 15:41
    1. DWORD is uint32_t in C++, thus UInt32 in C#.
    2. if(a & b) converts to if((a & b) != 0). != is evaluated before & thus the & expression needs parentheses around it.
    3. if(x) converts to if(x != 0)
    4. & is a 'bitwise and' in C#, like in C++.
    5. Depends on your C++ structure.
    0 讨论(0)
  • 2021-01-20 15:53

    Where you write :

    if (arg1 & arg2==0)

    The compiler understands :

    if (arg1 & (arg2==0))
    

    You should write :

    if ((arg1 & arg2) == 0)
    

    This is the way the C++ statement should be translated to C# :

    if (arg2 & 1) // C++ (arg2 is DWORD)
    if ((arg2 & 1) != 0) // C# (arg2 is Uint32)
    

    Or, in a more generic way:

    if (Flags & FlagToCheck) // C++
    if ((Flags & FlagToCheck) != 0) // C#
    

    In C/C++, 0 is false, everything else is true.

    1. You should check the definition of DWORD, it should be (unsigned int), which is UInt32 in C#
    2. if (integer & integer), in C/C++ means "if the result of the bitwise and between the two integers is not 0" (0 is false, everything else is true).
    3. if (!integer) means if (integer == 0) (again, 0 is false, everything else is true)
    4. in C#, like in Java I think, booleans and numbers are two different things, you can only use booleans in "if" statements, there is not implicit conversion if you use an int : it won't compile.
    5. I'll leave this one to someone else, I'd need to test to be sure...
    0 讨论(0)
  • 2021-01-20 15:56

    5 - It means both. Because LowPart and HighPart are just "windows" into QuadPart's memory, when result.LowPart == 1 and Result.HighPart == 0, then result.QuadPart will be equal to 1.

    0 讨论(0)
提交回复
热议问题