What is the easiest way to check an integer's remainder for modulus 2 in Nasm assembler?

风流意气都作罢 提交于 2019-12-19 11:46:31

问题


For example:

int x = 35;
if( x%2==1) { //do something }

I just want to check the modulus value without assigning the result to x.

Assume that value is in eax, so I can use DIV instruction, then put back the original value to eax etc.. but that seems inefficient. Can you suggest a better way?


回答1:


To branch according to the modulo 2 of a value in al/ax/eax/rax:

    test al,1
    jnz is_odd

is_even:
    ; do something for even numbers.

is_odd:
    ; do something for odd numbers.

However, if all you want is the modulo value, you don't need any branches.

test al,1
setnz bl   ; modulo 2 of al/ax/eax/rax is now in bl.



回答2:


If the low bit is on, it is not divisible by two:

test   x, 1
jne    somewhere_when_odd


来源:https://stackoverflow.com/questions/12764460/what-is-the-easiest-way-to-check-an-integers-remainder-for-modulus-2-in-nasm-as

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!