1
\$\begingroup\$

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
start:
 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
print_result:
 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?
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked May 11, 2017 at 17:09
\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

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
print_result:

And all you need to do is print the result:

call print_eax_binary
answered May 11, 2017 at 19:07
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.