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

前端 未结 3 370
时光说笑
时光说笑 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: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...

提交回复
热议问题