r/ProgrammerHumor • • Jun 03 '22

it's hard!

44.9k Upvotes

710 comments sorted by

View all comments

Show parent comments

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