Check if a number is odd or even (mathematical parity)

user3522262 picture user3522262 · Mar 27, 2015 · Viewed 17.5k times · Source

For a one digit number, I want to know if it's odd or even (multiple of 2). For example, given 9, print that is an odd number.

(i.e. check the mathematical parity, not the computing parity.)

This is what I have:

   assume cs:cseg,ds:dseg,ss:sseg
    cseg segment
    start:  
    mov ax, dseg
    mov ds, ax  
    
    mov ah, 01h ; Here, im adding a number
    int 21h 
    
    
    
    jp even
    jnp odd  
    
    even: 
    mov ah,09
    lea dx,par
    int 21h  
    jmp exit
    odd: 
    mov ah,09
    lea dx,odd1 
    int 21h   
    jmp salir
    salir:
    mov ax,4C00h
    int 21h
    
    cseg ends 
    
    dseg segment byte         
    even Db 'Even number$'
    odd11 Db 'Odd number$'
    dseg ends  
    
    sseg segment stack
    db 100h dup(?)
    sseg ends

end start

Answer

Alexander Zhak picture Alexander Zhak · Mar 27, 2015

To test if a number is odd or even, you check bit 0 of this number. if bit0 is set, then the number is odd. nothing else. Don't confuse PF (parity flag) and JP/JNP conditions. Parity Flag shows if the number of bits set in the least significant byte is even or odd.

From documentation:

PF (bit 2) Parity flag — Set if the least-significant byte of the result contains an even number of 1 bits; cleared otherwise.

Number 1 - odd number, 00000001b PF is cleared because there's only one bit set
Number 2 - even number, 00000010b, but PF is cleared again! because there's only one bit set
Number 3 - odd number, 00000011b, but PF set! because there're two bits set