neilobremski
Experienced Member
This afternoon I've been playing around with writing an itoa() equivalent in x86 assembler. The signature of this method is:
The general idea is to divide by the radix, write the remainder as the next digit (in a lookup table of [hexa] decimal characters), and then repeat the process on the quotient until it is zero. Then afterwards one merely reverses the string so that the digit values go highest to lowest rather than lowest to highest.
I couldn't find any mention of how this could be improved either by some fancy math or clever use of instructions. My first thought was that there must be some way to start with the highest digit and move to the lowest without the caller specifying the highest base. What I like about the itoa approach is that it doesn't use a fixed number of digits or space; it's very space efficient.
However, the disassembly I've seen from MSC 5.1's version of itoa does access memory 3x per digit: writing the digit, reading it to swap it, and writing it to swap it. Here's the assembler it uses to reverse the string.
I thought the use of LEA was a bit surprising here but there must have been good reason for it?
I don't have any specific question here, just a broad cast: does anyone have any enlightening innovations to share about this concept/method? I'd love to read them
void itoa(int input, char *buffer, int radix)
The general idea is to divide by the radix, write the remainder as the next digit (in a lookup table of [hexa] decimal characters), and then repeat the process on the quotient until it is zero. Then afterwards one merely reverses the string so that the digit values go highest to lowest rather than lowest to highest.
I couldn't find any mention of how this could be improved either by some fancy math or clever use of instructions. My first thought was that there must be some way to start with the highest digit and move to the lowest without the caller specifying the highest base. What I like about the itoa approach is that it doesn't use a fixed number of digits or space; it's very space efficient.
However, the disassembly I've seen from MSC 5.1's version of itoa does access memory 3x per digit: writing the digit, reading it to swap it, and writing it to swap it. Here's the assembler it uses to reverse the string.
Code:
DEC DI ; 670
LODSB ; 671
XCHG AL, [DI]; 672
MOV [SI-01], AL ; 674
LEA AX, [SI+01] ; 677
CMP AX, DI ; 67A
JB 0670 ; 67C
I thought the use of LEA was a bit surprising here but there must have been good reason for it?
I don't have any specific question here, just a broad cast: does anyone have any enlightening innovations to share about this concept/method? I'd love to read them