Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

x86 - assembly check if number is even

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 ax, 11;
    test ax, 1;

end: jmp end;
code_seg ENDS

And to check if number is even I look if zero flag is set. I know that the test instruction is like logical AND and that if result is 0 it sets zero flag. My question is: how this checks if number is odd/even? Actually I can't figure out why some even (binary) number and (logical and) 1 gives result of 0?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...