Public Group

# Packing 5bit colours into an uint

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

## 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 on other sites
Quote:
 Original post by ZeroSumI'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 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.

1. 1
2. 2
Rutin
31
3. 3
4. 4
5. 5
khawk
14

• 11
• 11
• 23
• 10
• 9
• ### Forum Statistics

• Total Topics
633647
• Total Posts
3013108
×