0

I have a python script with the below conditional in it and I need to convert it to C# yet I'm not sure how to interpret the conditional:

crc = 0xFFF
ch = 0x3C & 0xFF

if (ch & 1) ^ (crc & 1):
        #do code

If someone could explain to me how that if will be evaluated so I can create the same conditional in C# that would be greatly appreciated!

TPancakes
  • 31
  • 2
  • For numbers, `0` is treated as `False`, and everything else is treated as `True`. I.e. `0` is Falsey, everything else is Truthy. But in general, you call `bool()` on whatever result you are interested in to find out explicitly. – juanpa.arrivillaga Jan 02 '18 at 21:05
  • 2
    In C# you should be able to simply say `if (((ch & 1) ^ (crc & 1)) != 0) { ... }` assuming that `ch` and `crc` are of appropriate integral types. But the smarter thing to do is to ask yourself "what is the logical meaning of these operators?" The logical meaning of `&1` here is "extract the lower bit" and the logical meaning of `^` on a single bit is "not equal". So it would be better to write this as `if ((ch & 1) != (crc & 1)) { ... }` – Eric Lippert Jan 02 '18 at 21:15
  • 2
    Now ask yourself what would be better still. **You want to make the meaning of the code apparent from the text**. I would be inclined to write `static class Extensions { public static bool LowerBit(this int x) => (x&1) != 0;}` and then write your program as `if(ch.LowerBit() != crc.LowerBit())` and now it is *crystal clear* what is going on. Don't be cryptic. – Eric Lippert Jan 02 '18 at 21:19

0 Answers0