0

Possible Duplicate:
implement division with bit wise operator

I recently got into more depth by bitwise functions, and started to implement basic arithmetic functions with bitwise operators. So far I have gotten (+, -, *). However I'm not really sure how to approach division. I know that I could somehow use multiplication instead, but not sure how to approach this using that method either.

So how would I implement division using only bitwise operators these: (|, &, ~, ^, >>, <<) in C? For anyone who asks, this is not homework, just personal knowledge.

If you like, you can call the following functions in the code to make it easier (These are prewritten)

int badd(int n1, int n2);
int bsub(int n1, int n2);
int bmult(int n1, int n2);
Community
  • 1
  • 1
Rivasa
  • 6,510
  • 3
  • 35
  • 64

1 Answers1

0

Well, you can divide two integers without using any operators at all in C, assuming you have the standard library available:

int result = div(a, b).quot;

Note: this answer was purely rhetorical, but it was put out there to show the foolishness of attempting to write an entire dividing function in C, when the standard library (and the language itself) has support for it. Why would you re-write the wheel (even if just to learn) when the answer is already at your fingertips?

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
  • This isn't what I meant by function, I thought you would implement the code as a function. But nice work on the elegance. – Rivasa Sep 22 '12 at 01:26
  • @Link Haha, it was really a joke, dividing without using operators is certainly possible, but the question becomes why, when you could do it using an operator or assembly instruction. I also know of a way to do it using a `FILE *` and `fwrite` / `fread`, if you'd like to see that. – Richard J. Ross III Sep 22 '12 at 01:41
  • 6
    @RichardJ.RossIII: Comment on your note: To learn how things work. Same as saying "Because it's there" when asked why someone would climb Mount Everest. The "rhetorical" answer you gave is a prime example of my old saying: If you know how to use the function `SolveAllMathProblems()` you still don't know math. – Sani Huttunen Sep 22 '12 at 01:44