Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...