组装检查数字是否为偶数 [英] 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
然后检查数字是否为偶数,我看是否设置了零标志.我知道测试指令就像逻辑与,如果结果为0,它将设置零标志.我的问题是:如何检查数字是否为奇/偶?其实我不知道为什么有些偶数(二进制)和(逻辑与)1给出0的结果?
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?
推荐答案
未签名和已签名的数字( Two的补码)是奇数的:
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
因此 test
指令
test al, 1
检查是否设置了AL/AX/EAX/RAX的最低位.如果是,则数字为奇数.
可以使用 Jcc
说明进行检查,尤其是那些测试?ZERO
标记为
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
这篇关于组装检查数字是否为偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!