What is the best way to evenly scale one byte?
Question
In C I need to scale a uint8_t
from 0 - 255 to 0 - 31
What is the best way to do this evenly?
Solution
If you're trying to scale from 8 bits to 5 bits, you can do a 3 bit shift;
uint8_t scaled = (uint8_t)(original >> 3);
This drops the lower 3 bits.
OTHER TIPS
You can use some simple multiplication and division:
uint8_t scaled = (uint8_t)(((uint32_t)original * 32U) / 256U);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow