So what's the fastest way to test a number for being even or odd?

I see there is a parity flag but haven't been able to get 'jpo' to work as expected. I do need this to work for both positive and negative numbers.

I've tried:

(1)
mov eax, thenumber
test eax, eax
jpo odd

(2)
mov eax, thenumber
test eax, 1
jnz odd

really not sure why the parity thing isn't working (edit: ok it's just an even/odd number of 1's in base2. guess the parity flag isn't useful here). but is there some real fast trick or anything or is 'and eax, 1' the best thing to use?
Posted on 2004-09-03 07:22:28 by grv575
Please read up on parity flag. It is not used to see whether the data is even or odd.

The and/test is the best I guess.
Posted on 2004-09-03 07:29:43 by roticv
In other words, use your second routine to test if odd. You want to test whether the least significant bit is 1.

The first routine seems to test whether any bits are set at all in eax. I have not tried it but it may only fail with a value of zero.
Posted on 2004-09-03 08:54:38 by V Coder
mov eax, number
shr eax, 1
jc odd
Posted on 2004-09-03 09:26:48 by JimmyClif
indeed, parity is something totally different.
Posted on 2004-09-03 10:25:02 by lifewire
Shr eax,1, shr al,1 and test al,1 are the same size, but it might be that the latter is faster since it does not change the register.
Posted on 2004-09-03 11:01:37 by Sephiroth3
BT EAX, 0
JC HowOdd

...is another way, but might be slower. Usually there is a way to eliminate the branch.
Posted on 2004-09-07 22:54:53 by bitRAKE
So what's the fastest way to test a number for being even or odd?

I see there is a parity flag but haven't been able to get 'jpo' to work as expected. I do need this to work for both positive and negative numbers.

I've tried:

(1)
mov eax, thenumber
test eax, eax
jpo odd

(2)
mov eax, thenumber
test eax, 1
jnz odd

really not sure why the parity thing isn't working (edit: ok it's just an even/odd number of 1's in base2. guess the parity flag isn't useful here). but is there some real fast trick or anything or is 'and eax, 1' the best thing to use?


the parity bit in flag is telling the NUMBER that eax contains '1' is even or odd,
but not means whether eax is even or odd, which is same to its least significant bit is '0' or '1'.
Posted on 2004-09-08 01:28:16 by crquan
it also depends on what your action to be taken is when you know if the number is either odd or even. faster would be not doing a conditional jmp at all, but rather doing something like a CMOVcc, where possible.
Posted on 2004-09-08 02:54:35 by lifewire
To test odd or even, just test the lowest bit can simply do.

test eax,1
jz IsEven
Posted on 2004-09-08 03:57:26 by optimus

the parity bit in flag is telling the NUMBER that eax contains '1' is even or odd...

Actually no. The parity is always obtained only from the least-significant byte of the result.
Posted on 2004-09-08 15:20:02 by MazeGen