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

懵懂的女人 提交于 2019-12-01 22:23:49

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!