Hi fellow coders, I'm having trouble wrapping my mind around a confusing issue and need some clarification regarding how if statements are evaluating.
The following code works, but it shouldn't:
if ((preamble == 150) && ((curdata >> 16) == ~(curdata & 0xFFFF))) {
return(curdata & 0xFFFF);
}
In my transmitter code, the integer to be transmitted is shifted out, followed by its inverse. Here is the original thread in the hardware forum. In that thread,
I really don't know how it works like this. If curdata == 0xAAAA5555 and you put it through
((curdata >> 16) == ~(curdata & 0xFFFF))
then (curdata >> 16) = 0x0000AAAA
and ~(curdata & 0xFFFF) = 0xFFFFAAAAthis is because curdata & 0xFFFF evaluates first giving 0x00005555, then the ~ is evaluated giving 0xFFFFAAAA.
I don't understand how that expression can ever evaluate to true. If somebody knows that part of the puzzle please let me know! [smiley=huh.gif]
you might want to try something like this:
(((curdata >> 16) & 0xFFFF) == (~curdata & 0xFFFF))
Again this code shouldn't work, but does. It is returning (curdata & 0xFFFF) which should be the real integer's inverse. But, it is returning the actual number sent from the transmitter.
The following code still works like above, but is properly put together and reads correctly:
if ((preamble == 150) && ((curdata >> 16) == (~curdata & 0xFFFF))) {
return(curdata >> 16);
}
The two code snippets work the same, except the former returns (curdata & 0xFFFF) which really should be the inverse of the actual number, and the latter code returns it properly (curdata >> 16). Something about the way the if statement evaluates, is causing it to work when it shouldn't. It has something to do with ~(expression) changing the value held in curdata methinks.
Could someone please explain why the code above works like it does? Thanks In Advance.