Projectitis
Well-known member
Hi all,
EDIT: Nope this doesn't work for all ranges. Works for 4-bit to 2-bit back to 4-bit, and works for 8-bit to 4-bit and back to 8-bit, but not others.
Just putting this here for future searches, because I had to come up with this on my own when I couldn't find any results in my searches. Maybe I was using the wrong terms? Anyway:
During my work with different image pixel formats, I've often had to scale color values up and down. For example in most image formats, each color channel takes 8-bits (0-255), but on some displays, such as ILI9341, color channels are 5-bit (0-31) or 6-bit (0-64). Scaling down is straight-forward and well documented, just with a bit shift. However, I couldn't find any 'fast' solutions for scaling back up again.
Scaling down:
Scaling down is easy. You can shift-right >> by the correct number of bits and you get the correct value.
Scaling up:
Scaling up is more difficult, because simply shifting left << will not give the correct values. The formula seems to be:
I've tested with a few different bit levels and it seems to hold up. Could someone verify this method results in correct values? Is this a known method?
EDIT: Nope this doesn't work for all ranges. Works for 4-bit to 2-bit back to 4-bit, and works for 8-bit to 4-bit and back to 8-bit, but not others.
Just putting this here for future searches, because I had to come up with this on my own when I couldn't find any results in my searches. Maybe I was using the wrong terms? Anyway:
During my work with different image pixel formats, I've often had to scale color values up and down. For example in most image formats, each color channel takes 8-bits (0-255), but on some displays, such as ILI9341, color channels are 5-bit (0-31) or 6-bit (0-64). Scaling down is straight-forward and well documented, just with a bit shift. However, I couldn't find any 'fast' solutions for scaling back up again.
Scaling down:
Scaling down is easy. You can shift-right >> by the correct number of bits and you get the correct value.
Code:
// 8-bit number (0-255)
uint8_t n = 255;
// Change to 5-bit by shifting 3 bits
uint8_t m = n >> 3; // 31
Scaling up:
Scaling up is more difficult, because simply shifting left << will not give the correct values. The formula seems to be:
Code:
// 5-bit number (0-31)
uint8_t n = 31;
// Change to 8-bit by shifting 3 bits and adding self
uint8_t m = (n << 3) + n; // 255
I've tested with a few different bit levels and it seems to hold up. Could someone verify this method results in correct values? Is this a known method?
Last edited: