Use this:
unsigned int x = 150; unsigned int z = (x + 128) >> 8;
128 is the average, so after adding this rounding and 256=2^8 so that you can use the bit shift operation instead of division.
NOTE: this method only works for positive values.
If you need this for positive and negative values, you will need the following:
int x = -150; int z = (x >= 0 ? (x + 128) : (x - 128)) / 256;
NOTE: the bit-shift for signed values has some specific and not always trustworthy, so you cannot use this: int z = (x < 0) ? (x - 128) / 256 : (x + 128) >> 8; int z = (x < 0) ? (x - 128) / 256 : (x + 128) >> 8;
source share