Search code examples
c#bitmapbit-shift

Converting from RGB ints to Hex


What I have is R:255 G:181 B:178, and I am working in C# (for WP8, to be more specific)

I would like to convert this to a hex number to use as a color (to set the pixel color of a WriteableBitmap). What I am doing is the following:

int hex = (255 << 24) | ((byte)R << 16) | ((byte)G << 8) | ((Byte)B<<0);

But when I do this, I just get blue.

Any ideas what I am doing wrong?

Also, to undo this, to check the RGB values, I am going:

int r = ((byte)(hex >> 16)); // = 0
int g = ((byte)(hex >> 8)); // = 0
int b = ((byte)(hex >> 0)); // = 255

Solution

  • Try the below:

    using System.Drawing;
    Color myColor = Color.FromArgb(255, 181, 178);
    string hex = myColor.R.ToString("X2") + myColor.G.ToString("X2") + myColor.B.ToString("X2");