The MASM Forum Archive 2004 to 2012

General Forums => The Workshop => Topic started by: Turtle16 on March 22, 2005, 07:18:12 AM

Title: boolean odd / even
Post by: Turtle16 on March 22, 2005, 07:18:12 AM
I am new to MASM and need help using boolean instructions to determine if a number input is even or odd. xor? test? etc...Any help would be appreciated.
Title: Re: boolean odd / even
Post by: Petroizki on March 22, 2005, 07:32:47 AM
Just test for the first bit.

test eax, 1 ; the same as 'and', but doesn't modify eax
jnz odd
; even


The numbers go like this in bits:
0001 ; 1
0010 ; 2
0011 ; 3
0100 ; 4
0101 ; 5
etc...
Title: Re: boolean odd / even
Post by: AeroASM on March 22, 2005, 11:09:17 AM
Alternatively you could zero the first bit and see if is the same:


;save eax on stack
push eax
;zero the first bit
shr eax,1
shl eax,1
;test if same
pop ecx
cmp eax,ecx
je even
odd:
;
even:
;
Title: Re: boolean odd / even
Post by: roticv on March 22, 2005, 12:53:59 PM
Quote from: AeroASM on March 22, 2005, 11:09:17 AM
Alternatively you could zero the first bit and see if is the same:


;save eax on stack
push eax
;zero the first bit
shr eax,1
shl eax,1
;test if same
pop ecx
cmp eax,ecx
je even
odd:
;
even:
;

Why not just check the carry flag?
Title: Re: boolean odd / even
Post by: The_Grey_Beast on March 22, 2005, 03:48:25 PM
The best ways I know are:

1) like Petroizki said:

test ax, 1
jnz odd
even:
; even code

odd:
; odd code


2)
shr ax, 1
jc odd
even:
; even code

odd:
; odd code


The second one uses a shift, which modifies eax (divides it by 2). Also, it may be slower on processors such as 80x86, 286 or 386, since a shift is actually slower than an and operation (or test), but may be shorter (I think, correct me if I'm wrong).
Title: Re: boolean odd / even
Post by: AeroASM on March 22, 2005, 06:33:22 PM
It is shorter:

test eax,1
assembles to
A9,01,00,00,00

whereas

shr eax,1
assembles to
D1,E8

However, shr is twice as slow (on my computer (Pentium M 1.5GHz), 100 x test eax,1 takes 41 clock cycles but 100 x shr eax,1 takes 90 clock cycles)
Title: Re: boolean odd / even
Post by: Turtle16 on March 23, 2005, 04:04:19 PM
Thanks to everyone who replied. You have been a great help.