Gaming Your Way

May contain nuts.

Bitwise AND, IF and a big WTF

So what's wrong with this code:

if (this._iDrawLayer & ChipsGame.VIEW_LAYER_A == ChipsGame.VIEW_LAYER_A) {
// draw contents of layer A ...

nothing, really. Nonetheless it's not working in CS3 (yet again, prove me wrong).

Basically it's just the unoptimized check if a certain bit is set or not. Let's do some traces:

trace ("with ():", ((this._iDrawLayer & ChipsGame.VIEW_LAYER_A) == ChipsGame.VIEW_LAYER_A))
trace ("without ():", (this._iDrawLayer & ChipsGame.VIEW_LAYER_A == ChipsGame.VIEW_LAYER_A))
trace ("values :", this._iDrawLayer & ChipsGame.VIEW_LAYER_A , ChipsGame.VIEW_LAYER_A)

The result is this:

with (): true
without (): 1
values: 1 1

Interesting, isn't it?
It seems like the compiler chains the & and the == for some reason that escapes me...

So if you get something undesiered with bitwise operators ... use ( and ) around it.


Comments (3) -

  • Kriss

    11/4/2008 4:16:44 PM |

    That behavior is I believe right, the == kicks in before the &. Personally I tend to just shove brackets around everything anyway, just in case.

    Like a wise man once said, let's take off and nuke the site from orbit.

  • Mr. Ferris

    11/4/2008 5:02:54 PM |

    Shouldn't it be "&&"?

    You could also solve your problem with parenthesis.

    if( ( x && y ) == z ){}

    rather than

    if( x && y == z ){}

    Just a thought.

  • nGFX

    11/4/2008 5:36:17 PM |

    Hi Mr. Ferris,

    nope, using && is the "Logical AND" operator. (see:

    @ Kriss: yep, but I was lazy in the first place and just typed it down like that (it works, btw. in C# as far as I tested it) ... so basically I'm a "rather too many brackets" guy, just very lazy in this case ...


Comments are closed