assembly check if number is even

前端 未结 3 1528
小蘑菇
小蘑菇 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:52

    sadly am not very experienced with assembly, but in pseudocode there is a feature called "mod" which gives the remainder of a division.

    have a look here: Assembly Language - How to Do Modulo?

    for example:

    x = 3 z = x mod 2

    z would be 1, and if x were equal, z would be 0

    0 讨论(0)
  • 2020-12-19 17:53

    A (small) integer can be expressed in binary as b3 b2 b1 b0:

    b3 * 2^3  +  b2 * 2^2  +  b1 * 2^1  +  b0 * 2^0 =
    b3 *  8   +  b2 *  4   +  b1 *  2   +  b0 *  1
    

    where all bn values are either zero or one.

    The only way to get an odd number is if the least significant bit (b0) is 1.

    AND’ing a value with 1 (in binary, 0001) masks off all bits except the least significant bit (b0) ...

                b3  b2  b1  b0
    binary-AND   0   0   0   1
                --  --  --  --
                 0   0   0  b0
    

    ... giving a zero value if the least significant bit was zero (an even number), or a non-zero value (specifically 1) if the least significant bit was one (an odd number).

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题