Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 540
Toadums Avatar asked Nov 13 '12 02:11

Toadums


People also ask

How do you calculate hex code?

Now, to calculate the hexadecimal number, there are three quick steps (as also stated above): Multiply the first number (or converted number from the letter) by 16. Multiply the second number (or converted number from the letter) by 1. Add those two totals together to get a single value.


2 Answers

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");
like image 153
NoPyGod Avatar answered Oct 19 '22 13:10

NoPyGod


Using string interpolation, this can be written as:

$"{r:X2}{g:X2}{b:X2}"
like image 17
huysentruitw Avatar answered Oct 19 '22 13:10

huysentruitw