0

I am trying to convert an integer to string in order to output; but I am using the x86_64 and NASM assembly while the integer is 128-bit, in two registers. so I don't know how to output it; Thanks!

Prakash Darji
  • 990
  • 6
  • 13
CXWorks
  • 123
  • 1
  • 10
  • i can't use C functions and don't know how to divide this long int in assembly – CXWorks Mar 21 '16 at 12:38
  • This question is already discussed, click [here](http://stackoverflow.com/questions/13523530/printing-an-int-or-int-to-string). Isn't your solution? – Prakash Darji Mar 21 '16 at 12:39

1 Answers1

0

Here's an (assembly-style) algorithm you can use for an unsigned integer. Start with the number n:

start:
    if n is non-zero then goto nonZeroNum.
    output '0'.
    return.

nonZeroNum:
    set digitCount to zero.
numLoop:
    get n modulo 10 and push it onto the stack.
    increment digitCount.
    divide n by 10 (integer division).
    if n is non-zero then goto numLoop.

digitLoop:
    pop digit.
    convert number to character (eg, adding 48 for ASCII).
    output that character.
    decrement digitCount.
    if digitCount is non-zero then goto digitLoop.

That should be a good start, I'd suggest running it through you wetware manually so that you understand how it works.

Then you simply need to work out the assembly instructions that will do what the pseudo-code does. That shouldn't be too onerous since it's likely to be a one-to-one mapping.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • i know the way, but i don't know how to divide....For n is in two registers, but the instructions only deal with 64b/64b (I am not sure) – CXWorks Mar 21 '16 at 12:58
  • Instead of division you could use repeated subtraction. That's easy for any bit width. It also gives you the result in the correct order without having to mess with the stack ;) – Jester Mar 21 '16 at 13:09
  • Use the `DIV` (unsigned) or `IDIV` (signed) instruction depending on whether your 128-bit integer is unsigned or signed. You put the upper 64-bits into the `RDX` register and the lower 64-bits into the `RAX` register before the instruction. Then if you store 10 into `RBX` then the instruction `DIV RBX` will divide by 10 and put the quotient into `RAX` and the remainder into `RDX` (writing over their original contents). – pcarter Mar 21 '16 at 13:22
  • 1
    @pcarter, the problem is that if the quotient can't fit in RAX then you get a divide error. Try dividing 2^120 (a large value that fits in a 128-bit integer RDX:RAX) by 10. The quotient can't be represented in 64 bits and a divide error is generated. – Michael Petch Mar 21 '16 at 13:45
  • thx to all of u, I may deal like this: divide n by 10^k, let 10^k < 2^64, then deal with the quotient and remainder separately, hope the num not too long ....in fact , the only reason is i am too lazy to write the algorithm – CXWorks Mar 21 '16 at 15:00