Skip to content
Advertisement

Printing an integer with x86 32-bit Linux sys_write (NASM)

I’m new to this forum. I have a little experience with high-level languages (really little). Nearly one month ago I thought it would be a good idea to see how assembly worked so after choosing nasm (IA-32) on linux I started learning from a tutorial.

Now, after ending it, I tried to write a simple program where you get the computer to print a list of 100 number (1 2 4 8 16…) but I couldn’t even get it right. I get this output:

JavaScript

The program is this:

JavaScript

It looks like the error is in the part that doubles the number or the one that stores it in the variable ‘num’, yet I don’t understand why it happens and how to solve it.

By the way can someone explain me when to use the square brackets exactly? Is there a rule or something? The tutorial calls it “effective address” and it looks like I have to use the brackets when I want to move (or do something with) the content of a variable instead of doing it to the variable’s address. Yet I’m quite confused about it. I see it used in:

JavaScript

But isn’t it obvious that one wants to increment the content of the register (since it doesn’t have an address (or does it?) ??

Advertisement

Answer

Your numbers will quickly grow larger than just a single digit. What you ought to be doing is have an integer in num rather than a character, and then convert that integer into a string that you can print with sys_write.

Here’s one way of doing the conversion: repeated division by 10, getting the lowest digit first as the remainder:

JavaScript

Which you can use like this:

JavaScript

Your number-doubling can be simplified to shl dword [num],1. Or better, double it at some point while it’s still in a register with add eax,eax.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement