The following exercise is from an Assembler-course I'm taking:

Write a program that takes a number x as input, and returns:

  • 0 if x is even.
  • 1 if x is odd.

Full exercise-page here: GitHub

Here's my solution:

format PE console
entry start

include 'win32a.inc' 

; ===============================================
section '.text' code readable executable


    call    read_hex        ; Provided by the teacher. Reads a hexadecimal number from stdin.

    and     eax,    0x1

    cmp     eax,    0x0 
    je      print_result

    mov     eax,    0x1
    call    print_eax_binary    ; Provided by the teacher. Prints a binary number to stdout.

    ; Exit the process:
    push    0
    call    [ExitProcess]

include 'training.inc'

I would say it works alright:

enter image description here

  • Is my solution valid?
  • Can it be improved? Respectively, is there a better solution possible?

Here are some things that may help you improve your code.

Simplify your code

This can certainly be simplified. Keep the goal in mind: get either 0 or 1 into EAX. Once you've executed this instruction:

and     eax,    0x1

That's exactly what you have. So that means all of this can be deleted:

    cmp     eax,    0x0 
    je      print_result

    mov     eax,    0x1

And all you need to do is print the result:

call    print_eax_binary

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.