r/dailyprogrammer • • Aug 05 '12
[8/3/2012] Challenge #85 [difficult] (Bitwise arithmetic)
While basic arithmetic operations like addition, subtraction, multiplication, etc. seem 'natural' to us, computers think on a very different level: under the hood, computations work with bitwise operations, using operators like ~, &, |, ^, and <<. Your task is to implement functions for (integer) addition, subtraction, negation, multiplication, division, modulo, and exponentiation, without using any "high-level" operators like + and *. Other statements like "if" and "while", or recursion for functional languages, are fine.
As a hint, you could start with a helper function that increments a binary number, and work from there. Your functions should take signed integer arguments and return signed integer values, rounding down (e.g. binary_div(14, 4) == 3, not 3.5).
Use your set of functions to implement this function:
f(a, b, c, d, e) = (a % e) * (b / (c - a) + exp(d * (-b), e))What is the result of f(50, -40, 300, 2, 3)?
View all comments
Show parent comment
1
u/push_ecx_0x00 Aug 05 '12
I managed to get 32-bit addition working in c++ (well, mostly c), but it's a shitty implementation. Maybe it can help. I basically used Adders, but I accidentally made it way more complicated than it needed to be. The rest of the operators OP mentioned can be built on top of addition (with the exception of modulus, division, and subtraction) using some method like this.
my shitty code: http://pastie.org/4396528