News:

MASM32 SDK Description, downloads and other helpful links
MASM32.com New Forum Link
masmforum WebSite

boolean odd / even

Started by Turtle16, March 22, 2005, 07:18:12 AM

Previous topic - Next topic

Turtle16

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.

Petroizki

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...

AeroASM

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:
;

roticv

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?

The_Grey_Beast

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).

AeroASM

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)

Turtle16

Thanks to everyone who replied. You have been a great help.