2

I'm storing a 3 value RGB representation into an 16bit integer by bit shifting it based off an answer from here (Convert RGB values to Integer). It seems to work for the g and b values, but r is always returned as 0.

My code is:

uint16_t rgb = ((r&0x0ff) << 16) | ((g&0x0ff) << 8) | (b&0x0ff);
        qDebug() << "wrote rgb: " << rgb;
        qDebug() << "wrote r: " << r << " g: " << g << " b: " << b;
        qDebug() << "unshifted r: " << ((rgb >> 16) & 0x0ff) << " g: " << ((rgb >> 8) & 0x0ff) << " b: " << (rgb & 0x0ff);
Community
  • 1
  • 1
Nicholas Smith
  • 11,642
  • 6
  • 37
  • 55

2 Answers2

5

You're using a 16bit int, and shifting your red value by 16 bits, so you're effectively just doing r = 0. You're literally shifting your values past the end of the available space. To store three 8 bit values, you need at LEAST 24 bits, meaning you'll have to use a uint32_t instead.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • I have to store them in a uint16_t unfortunately otherwise I would. I'm going to change them into a 5 bit representation instead. – Nicholas Smith Sep 25 '13 at 15:24
5

If you need to store RGB in a 16-bit integer, you can only store the colors with limited resolution. Typically you use 5 bits each for red and blue, and 6 bits for green.

This was once fairly common -- while it does reduce color resolution, the result remains fairly usable for many purposes (business graphics and such, but not decent photo editing or anything like that where color accuracy matters).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • Thanks, I posted and then realised what I'd done wrong. I'm going to shift them to 5bit representations as the colour accuracy doesn't need to be 100% exact. – Nicholas Smith Sep 25 '13 at 15:24