assembly check if number is even

前端 未结 3 1612
小蘑菇
小蘑菇 2020-12-19 17:16

I have homework to write assembly code for checking if number is odd or even. I have this code

code_seg SEGMENT
    ASSUME cs:code_seg, ds:data_seg;

    mov         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-19 17:56

    Both unsigned and signed numbers (Two's complement) are odd if the lowest bit is set:

    00000001 = 1    (odd)    // unsigned, or signed positive
    11111111 = 255  (odd)    // unsigned
    01111111 = 127  (odd)    // unsigned, or signed positive
    10000001 = -127 (odd)    // signed negative
    11111111 = -1   (odd)    // signed negative
    

    So the test instruction

    test al, 1
    

    checks if the lowest bit of AL/AX/EAX/RAX is set. If it is, the number is odd.
    This can be checked using the Jcc instructions, especially those testing the ?ZERO flag with

    JNZ target    ; jump if odd  = lowest bit set
    JZ  target    ; jump if even = lowest bit clear = zero
    

提交回复
热议问题