Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement division with bit-wise operator

How can I implement division using bit-wise operators (not just division by powers of 2)?

Describe it in detail.

like image 862
TimeToCodeTheRoad Avatar asked Mar 12 '11 19:03

TimeToCodeTheRoad


1 Answers

The standard way to do division is by implementing binary long-division. This involves subtraction, so as long as you don't discount this as not a bit-wise operation, then this is what you should do. (Note that you can of course implement subtraction, very tediously, using bitwise logical operations.)

In essence, if you're doing Q = N/D:

  1. Align the most-significant ones of N and D.
  2. Compute t = (N - D);.
  3. If (t >= 0), then set the least significant bit of Q to 1, and set N = t.
  4. Left-shift N by 1.
  5. Left-shift Q by 1.
  6. Go to step 2.

Loop for as many output bits (including fractional) as you require, then apply a final shift to undo what you did in Step 1.

like image 136
Oliver Charlesworth Avatar answered Sep 23 '22 15:09

Oliver Charlesworth