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.

C/C++ > Will this test if my number is an odd number?

#14561 - Geoff - Thu Jan 08, 2004 6:49 pm

source wrote:

#define BIT0 1

if(counter & BIT0) { //tests if the counter is an odd number


'counter' is an unsigned integer that increments once every frame. Is this doing what I think it's doing (simply testing if counter is odd) or is it doing something else too? Like changing counter?

#14563 - Lord Graga - Thu Jan 08, 2004 7:50 pm

yes, it checks if it's odd.

#14564 - LOst? - Thu Jan 08, 2004 8:05 pm

Geoff wrote:
source wrote:

#define BIT0 1

if(counter & BIT0) { //tests if the counter is an odd number


'counter' is an unsigned integer that increments once every frame. Is this doing what I think it's doing (simply testing if counter is odd) or is it doing something else too? Like changing counter?


You forget to increament it each time:

Quote:
int counter;
if (++counter & 1);

#14570 - sajiimori - Thu Jan 08, 2004 8:24 pm

lol, he didn't post his entire source you know! You may as well tell him that he forgot to write a main().

#14595 - Geoff - Fri Jan 09, 2004 2:21 am

Awesome. I used to be very sloppy and test if(counter%2==1) but I've since learned that that's slowwwww.

#14596 - poslundc - Fri Jan 09, 2004 2:40 am

You can replace "% n" with "& (n-1)" whenever n is an even power of two.

This is extremely important in GBA programming, since as you observed there is no hardware divide, which means the modulus operator (%) is emulated in software and is slow as heck. But the bitwise-and operator (&) requires only one ALU instruction.

It also makes it extremely convenient that so many aspects of the GBA (sprite/tile widths, background sizes, palette sizes, etc.) are even powers of two.

Dan.

#14599 - LOst? - Fri Jan 09, 2004 3:11 am

Geoff wrote:
Awesome. I used to be very sloppy and test if(counter%2==1) but I've since learned that that's slowwwww.


Yea, one thing for sure. Don't use modulo with the GBA :P

#14608 - tom - Fri Jan 09, 2004 10:19 am

btw, gcc is smart enough to implement "% n" by "& (n-1)" if n is a power of two.