Is there a way to test if a number is even?

Blitz3D Forums/Blitz3D Beginners Area/Is there a way to test if a number is even?

n8r2k,

The number (call it n) is stored in binary as a 4 byte integer in memory. Say that n = 3, it will look like this in binary:

11

That's 2 + 1 = 3. If n = 6 it will look like this:

110

That's 4 + 2 = 6. If n = 1 it will look like this:

1

1 = 1. So when you do an AND it compares each binary digit (bit), and if they are 1 in both numbers that digit is 1 in the result. If either number has a 0 for that digit, it is 0 in the result. Therefore:

011 AND 001 = 001
110 AND 001 = 000

Here's the same thing in decimal:

3 AND 1 = 1
6 AND 1 = 0

Since any even number will have a 0 for the rightmost bit, and any odd number will have 1, you will get a result of 1 for any odd number and a result of 0 for any even number.

If this doesn't make sense, read up on how binary numbers work and reread :)