c - Trick to divide a constant (power of two) by an integer -


note theoretical question. i'm happy performance of actual code is. i'm curious whether there alternative.

is there trick integer division of constant value, integer power of two, integer variable value, without having use actual divide operation?

// fixed value of numerator #define signal_pulse_count 0x4000ul  // division use neat trick. uint32_t signaltoreferenceratio(uint32_t referencecount) {     // promote numerator 64 bit value, shift left 32     // result has adequate number of bits of precision, , divide     // numerator.     return (uint32_t)((((uint64_t)signal_pulse_count) << 32) / referencecount); } 

i've found several (lots) of references tricks division constant, both integer , floating point. example, question what's fastest way divide integer 3? has number of answers including references other academic , community materials.

given numerator constant, , it's integer power of two, there neat trick used in place of doing actual 64 bit division; kind of bit-wise operation (shifts, and, xor, kind of stuff) or similar?

i don't want loss of precision (beyond possible half bit due integer rounding) greater of doing actual division, precision of instrument relies on precision of measurement.

"let compiler decide" not answer, because want know if there trick.

extra, contextual information

i'm developing driver on 16 bit data, 24 bit instruction word micro-controller. driver magic peripheral modules obtain pulse count of reference frequency fixed number of pulses of signal frequency. required result ratio of signal pulses reference pulse, expressed unsigned 32 bit value. arithmetic function defined manufacturer of device i'm developing driver, , result processed further obtain floating point real-world value, that's outside scope of question.

the micro-controller i'm using has digital signal processor has number of division operations use, , i'm not afraid if necessary. there minor challenges overcome approach, beyond putting assembly instructions make work, such dsp being used pid function in bldc driver isr, nothing can't manage.

you cannot use clever mathematical tricks not division, can of course still use programming tricks if know range of reference count:

  • nothing beats pre-computed lookup table in terms of speed.
  • there fast approximate square root algorithms (probably in dsp), , can improve approximation 1 or 2 newton-raphson iterations. if doing computation floating-point numbers accurate enough you, can beat 64bit integer division in terms of speed (but not in clarity of code).

you mentioned result converted floating-point later, might beneficial not compute integer division @ all, use floating point hardware.


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -