Jump to content
  • Advertisement
Sign in to follow this  
ZeroSum

Packing 5bit colours into an uint

This topic is 3645 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm trying to pack three five bit colours into an unsigned int (C#) to write to a binary file. I've done this before but I can't remember for the life of me how to do it. I know how to read the values by shifting and bit masking (below) but how do I reverse it?
currentVal = reader.ReadUInt16();
r = currentVal & 0x1F;
g = (currentVal >> 5) & 0x1F;
b = (currentVal >> 10) & 0x1F;

Thanks.

Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by ZeroSum
I'm trying to pack three five bit colours into an unsigned int (C#) to write to a binary file. I've done this before but I can't remember for the life of me how to do it.

I know how to read the values by shifting and bit masking (below) but how do I reverse it?


UInt16 value15 = ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3);

You cannot combine the shifts, it will leave extra bits, which will affect lower color bits. Unless you mask the color first, but that will probably eat as many cycles as the two shifts:

UInt16 value15 = ((r & 0xf8) << 7) | ((g & 0xf8) << 2) | (b >> 3);

This is assuming r, g, and b are 0-255. If they are already in 5 bit format, you can eliminate the '>> 3' for each color.

Or for 16 bit color:
UInt16 value16 = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3);

Share this post


Link to post
Share on other sites
Thank you it works great:

newColour = (b << 10) | (g << 5) | r;


I forgot that you had to shift and then OR them. It's actually for converting images to the DS's texture format hence the 5bit colour.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!