Here is one of the more interesting applications, a function that converts a 16-bit word in a register to a string of 4 hex digits in only 24 bytes of code, and can also be called to convert bytes and nybbles (x86):
; output value of AX as four hex digits to ES:DI
write_hex_word:
xchg al, ah
call write_hex_byte
xchg al, ah
; output value of AL as two hex digits to ES:DI
write_hex_byte:
push ax
shr al, 4
call write_hex_nybble
pop ax
; output lower nybble of AL as hex digit to ES:DI
write_hex_nybble:
and al, 15
cmp al, 10
sbb al, 69h
das
stosb
retOf course, your cow-orkers might wish you hadn't, depending on the amount of restraint you can summon :-)
int x2(int x) { return x + x; }
int x4(int x) { return x2(x) + x2(x); }
int x8(int x) { return x4(x) + x4(x); }
int x16(int x) { return x8(x) + x8(x); }
int x32(int x) { return x16(x) + x16(x); }Maybe I don't understand what the word recursion means, but I thought that you'd have to call yourself directly or indirectly.
You could state it that the multiple by a power of two is the sum of the multiples of one order of magnitude base 2 lower.
By these definitions, all but the most trivial code is recursive.
// e is a power of two
int mult(x, e)
return e==1 ? x : mult(x, e/2) + mult(x, e/2)
endThe piece of code in question was to use the chip as a smart power controller. Worked pretty well, aside from the limited code space.
Here's a blog entry about the little project: http://www.dadhacker.com/blog/?p=1911
Apparently the original code did multiplies by 10s, so the leaf routine was a few more instructions.
First of all, that's the top 0.01%. Second of all, with that strategy, no you don't because the top 0.01% are going to walk out of interviews that ask dumb brain teasers. The best programmers are ones who can solve problems in the context of a team and codebase, with the help of the internet and iteration, not solve obscure but not-really-that-hard problems in 15 minutes.
Then one day I got one to laugh at this byte-saving routine to do some multiplications:
Recursion. In assembly language. We were six bytes shy of filling our code space, but we had gobs of stack, and I got about 60 bytes back from our stupid compiler with this. When my cow-orker saw it, he thought for a moment, smiled, said "You're one sick dude, you know that?" and we checked it in.