gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

Beginners > Problem with "&" operator

#29199 - identitycrisisuk - Sat Nov 13, 2004 4:42 pm

I've read a few things before about using & (n-1) instead of % n but this is the first time I've had to use it. AFAIK these two code segments should be equivalent:

Code:

if(Moving())
{
   if(++m_animCount > 8)
   {
      ++m_walkFrame;
      m_animCount = 0;
   }
   if(m_walkFrame > 2) m_walkFrame = 0;
   m_nextLower = WALK0+m_walkFrame;
}

if(Moving())
{
   if((++m_animCount) & (8-1))
   {
      ++m_walkFrame;
   }
   if(m_walkFrame > 2) m_walkFrame = 0;
   m_nextLower = WALK0+m_walkFrame;
}

However, only the first example results in a decrease in speed of the animation that I'm trying to do. The second just makes the character move in Benny Hill vision with the frame of animation appearing to change every frame. There's excessive brackets as I was trying to make sure I knew exactly what I was doing. At least the first way works but I'd like to know why the second isn't as it's nicer and I will probably need it in future.

#29200 - poslundc - Sat Nov 13, 2004 5:11 pm

& (n-1) is equivalent to % for even powers of two, but that's not your problem. The two code segments are fundamentally different: the first code segment evaluates to true whenever m_animCount turns 9 (once every nine frames). The second code segment evaluates to false whenever m_animCount is an even multiple of 8 (once every eight frames).

So, you're not counting on the same interval, and you're evaluating opposite conditions.

Dan.

#29201 - sajiimori - Sat Nov 13, 2004 6:00 pm

Also, don't worry about using n&(m-1) because the compiler will automatically do the conversion when it's possible.

#29202 - identitycrisisuk - Sat Nov 13, 2004 6:00 pm

*slaps forehead*

Thank you, I feel such a moron now, should have thought some more before posting...

*goes away feeling sheepish*