0

I was wondering if there was an easy way to divide a number with range [0,99] by 10, by simply doing bit-wise operations such as shift, add, subtract etc. I am looking for a solution that would work in an 8-bit wide register because I saw some solution that involved making an approximation using 32 bits.

Pure
  • 85
  • 1
  • 8
  • 2
    Possible duplicate of [Divide by 10 using bit shifts?](http://stackoverflow.com/questions/5558492/divide-by-10-using-bit-shifts) – Ashigore Mar 31 '16 at 18:25
  • If you read the question carefully I am saying that I am working with an 8 bit wide register. The answer to that question involves shifting a number by 32. – Pure Mar 31 '16 at 18:41

2 Answers2

1

Given the limited range (there are only 10 possible results), you might do better with a kind of binary search: if n<50 then if n<30 then if n<10 then return 0 else if n<20 return 1 else return 2 else if n<40 return 3 else return 4 else ...(handle 5..9)

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

The method specified here can be generalized for any bit width. Basically, find (1/10) * 2**(bit width) then multiply that by the divisor and right shift by the bit width.

Programmatically using javascript, this is:

function bitwiseDivApprox(dividend) {
    var divisor = 26; // Math.ceil((1/10) * Math.pow(2, 8))
    return (divisor * dividend) >> 8;
}

(this being said, it probably isn't worth it to try to optimize this for very small numbers)

Community
  • 1
  • 1
Peter G
  • 2,773
  • 3
  • 25
  • 35