Note that there are some explanatory texts on larger screens.

plurals
  1. POSmallest method of turning a string into an integer(and vice-versa)
    primarykey
    data
    text
    <p>I am looking for an extremely small way of turning a string like <code>"123"</code> into an integer like <code>123</code> and vice-versa.</p> <p>I will be working in a freestanding environment. This is NOT a premature optimization. I am creating code that must fit in 512 bytes, so every byte does actually count. I will take both x86 assembly(16 bit) and C code though(as that is pretty easy to convert) </p> <p>It does not need to do any sanity checks or anything..</p> <p>I thought I had seen a very small C implementation implemented recursively, but I can't seem to find anything for size optimization.. </p> <p>So can anyone find me(or create) a very small atoi/itoa implementation? (it only needs to work with base 10 though)</p> <p>Edit: (the answer) (edited again because the first code was actually wrong) in case someone else comes upon this, this is the code I ended up creating. It could fit in 21 bytes!</p> <pre><code>;ds:bx is the input string. ax is the returned integer _strtoint: xor ax,ax .loop1: imul ax, 10 ;ax serves as our temp var mov cl,[bx] mov ch,0 add ax,cx sub ax,'0' inc bx cmp byte [bx],0 jnz .loop1 ret </code></pre> <p>Ok, last edit I swear! Version weighing in at 42 bytes with negative number support.. so if anyone wants to use these they can.. </p> <pre><code> ;ds:bx is the input string. ax is the returned integer _strtoint: cmp byte [bx],'-' je .negate ;rewrite to negate DX(just throw it away) mov byte [.rewrite+1],0xDA jmp .continue .negate: mov byte [.rewrite+1],0xD8 inc bx .continue xor ax,ax .loop1: imul ax, 10 ;ax serves as our temp var mov dl,[bx] mov dh,0 add ax,dx sub ax,'0' inc bx cmp byte [bx],0 jnz .loop1 ;popa .rewrite: neg ax ;this instruction gets rewritten to conditionally negate ax or dx ret </code> </pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload