Jerry said:
I want an algorithm that do arithmetic operations(divide,mutiply,add
etc.)just using bitwise operators:<<,>>,&,|,^;
For example,how "a/10" can be implemented.
Oddly enough, just the other day I figured out how to do increment or
decrement by a value 2^n. With enough fiddling you could do arbitrary
addition and subtraction by any value (2's complement if you want to
use for signed values.) Some more fiddling would allow you to use 100
byte or 200 byte values--though you could do the same using + and -
creatively.
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#define INT_BIT (CHAR_BIT * sizeof(int))
int main(void) {
int L, leftShift, i, changeMask;
leftShift = 0; /* added or subtracted value will be 2^leftShift */
i = 25; /* value we are adding to or subtracting from */
changeMask = 1 << leftShift;
for (L = leftShift; L < INT_BIT; L++) {
i ^= changeMask;
if ( /* ! */ (i & changeMask)) { /* comment in or out "!" for
addition or subtraction */
break;
}
changeMask <<= 1;
}
printf("%i", i);
return 0;
}
Knowing that this would work came about from fiddling with a binary
tree (...it would take a bit to explain beyond that.) Though I am not
sure there is any point in creating such code--I do believe that
processors boil down mathematical operations to logical operations, but
I would have to assume intel has a better algorithm than this.
-Chris