3

I use a simple uint8_t to store a real value between 0.0 and 1.0, with 0 being mapped to 0.0 and 255 being mapped to 1.0, and linear interpolation in-between.

Obviously i can multiply this numbers with the following procedure:

  • divide them / 255.0f
  • multiply the resulting floats
  • convert the result back to the uint8-range (uint8_t)(result * 255.0f)

However i wonder if there exists an easier way which produces the same result without involving the float conversion (i.e. some black magic bit fiddling or shifting)?

Any help would be appreciated!

Askaga
  • 6,061
  • 5
  • 25
  • 49
  • look over this thread several different interpolation methods are shown http://stackoverflow.com/questions/1102692/how-to-do-alpha-blend-fast – Dreamwalker May 24 '13 at 10:22
  • the "divide by 255"-answer does exactly what i need. perfect! thanks! – Askaga May 24 '13 at 10:26
  • 1
    Your procedure gives a code like `(uint8_t)(((a / 255.0f) * (b / 255.0f)) * 255.0f)`. That can be rewritten `(uint8_t)(((a * b) / (255.0f * 255.0f)) * 255.0f)`, then `(uint8_t)((a * b * 255.0f) / (255.0f * 255.0f))`, which simplifies into `(uint8_t)((a * b) / 255.0f)`, or simply `(uint8_t)(a * b / 255)`, using only integer multiplication and division (the cast is still needed to convert back from `int`). – gx_ May 24 '13 at 10:34
  • @BillAskaga I was going to link that one originaly but decided the whole thread is worth a read :) – Dreamwalker May 24 '13 at 10:36

0 Answers0