C# Programming > Drawing

C# Color to uint
uint to Color

Color and uint

C# allows programmers to work with colors in a bunch of different ways. One technique is to convert Color to uint and back, uint to Color. The apply commonly is to create mask colors, for custom-shape Windows Forms for example.

Remember that uint is not the same thing as int. Uint is an unsigned integer, meaning it allows programmers to work with pointers. This is helpful when you want to progress images fast, when working with pointers gives a huge boost in speed.

Convert Color to uint

As you probably already know, a Color object in C# holds four values: Alpha, Red, Green, Blue. In order to assign those values to a single unsigned integer (uint) you have to make use of the shift operator:

private uint ColorToUInt(Color color)
{
      return (uint)((color.A << 24) | (color.R << 16) |
                    (color.G << 8)  | (color.B << 0));
}

It is fairly simple then to convert any Color to uint.

Convert uint to Color

If you instead have a pointer stored in a uint, to convert the uint to Color then you have to use the shift operator in the opposite direction:

private Color UIntToColor(uint color)
{
     byte a = (byte)(color >> 24);
     byte r = (byte)(color >> 16);
     byte g = (byte)(color >> 8);
     byte b = (byte)(color >> 0);
     return Color.FromArgb(a, r, g, b);
}

Each value of the Color is being shifted back the same amount as before, except the other direction. The important part is to convert the values to byte, if you try to convert to int the function will fail. With byte, the function works to convert any valid uint to Color.

Conclusion

The functions to convert Color to uint and uint to Color are stand-alone and can be added to any project.

OfficeButton

Back to C# Article List