How do you return 'not uint' in C#?

蹲街弑〆低调 提交于 2019-12-02 02:00:52

问题


I have some code written in VB that reads as follows:

Return (Not (crc32Result))

I am trying to convert it to C#, and this is what I have:

return (!(crc32Result));

However I get a compiler error:

Compiler Error Message: CS0023: Operator '!' cannot be applied to operand of type 'uint'

Is there a different operator I need to be using instead of this one?

Thanks!


回答1:


It looks like what you are trying to do is reverse the bits of crc32result. If so, you want the tilde operator ~.

return (~crc32Result);

Reference this question.




回答2:


In C#, the bang(!) is used to flip a boolean variable. Are you trying to treat the uInt above as a boolean, or perform some other reversal (reversal of all binary digits, perhaps)?

I'd suggest one of these is the solution you're looking for:

return (!(bool)crc32Result);  // treating as bool (0 = false, anything else is true)

return (~crc32Result); //bitwise flipping for all



回答3:


Try this:

return crc32Result == 0;

Or to be a little clearer on what I'm doing:

return !(crc32Result != 0);

What the second example does is convert it to boolean by the principal of "0 is false, non-zero is true". So if it's not equal to zero, it will return true. And then I use the '!' operator to do the "not" operation. The Visual Basic code you gave apparently does the first part implicitly (as will C/C++), but C# and Java won't.

But this is if and ONLY if you're looking for a boolean return type from the function. If you're doing a bit-wise inversion, then you need the following:

return (~crc32Result);

In that case, the '~' operator does the conversion to the other bit pattern.



来源:https://stackoverflow.com/questions/1179574/how-do-you-return-not-uint-in-c

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