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

前端 未结 3 718
醉酒成梦
醉酒成梦 2021-01-23 02:56

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:

相关标签:
3条回答
  • 2021-01-23 03:42

    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.

    0 讨论(0)
  • 2021-01-23 03:43

    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
    
    0 讨论(0)
  • 2021-01-23 03:54

    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.

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