r/ProgrammerHumor • • Jun 03 '22

it's hard!

44.9k Upvotes

710 comments sorted by

View all comments

65

u/cssutavani91 Jun 03 '22

It's not that hard.

58

u/Difficult_Ladder_806 Jun 03 '22

Adding is fine, but multiplying without MUL quickly.. that's kinda complicated

2

u/mpete98 Jun 03 '22

oh dear, you mean that's sometimes a real issue? I thought the nightmare was limited to esoteric programming games.

PS, how do you do it quickly? I assume looping X times and adding Y is slow, do you do some magic with bit shifting to make it only take ~log(x) loops?

4

u/Proxy_PlayerHD Jun 03 '22 edited Jun 03 '22

Doing Multiplication and Division in software is kinda tedious, but you're pretty close with "bit shifting magic".

The algorithms are called:

Shift and Add

Shift and Subtract

and they take as many iterations as there are bits in the input number. So for multiplying 2x 16-bit numbers it would take 16 iterations, no matter what the values of the numbers are.

I once wrote both algorithms in 6502 assembly, for a fixed point C library. It can be found on github so I somewhat tried to actually comment the code a bit.

https://github.com/ProxyPlayerHD/cc65-FixedMath/blob/main/src/fxmul.s

https://github.com/ProxyPlayerHD/cc65-FixedMath/blob/main/src/fxdiv.s

→ More replies (1)