简体   繁体   中英

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

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!

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.

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

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.

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