Ehsan Akbar
Ehsan Akbar

Reputation: 7299

convert RGB int value to Hex format with 0x prefix in c#

I am trying to convert an RGB value to hex format in c# using this code :

int ColorValue = Color.FromName("mycolor").ToArgb();
string ColorHex = string.Format("{0:x6}", ColorValue);

The colorHex value likes this format ffffff00 but i need to change it like this :0x0000.how can i do that?

Best regards

I am so new in c# form application .

Upvotes: 0

Views: 3159

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503839

Just add the 0x part yourself in the format string:

// Local variable names to match normal conventions.

// Although Color doesn't have ToRgb, we can just mask off the top 8 bits,
// leaving RGB in the bottom 24 bits.
int colorValue = Color.FromName("mycolor").ToArgb() & 0xffffff;
string colorHex = string.Format("0x{0:x6}", colorValue);

If you want capital hex values instead of lower case, use "0x{0:X6}" instead.

Upvotes: 4

Steve
Steve

Reputation: 216363

If you want only the 3 bytes that define the RGB part of the color you could try this

    Color c = Color.FromName("mycolor");
    int ColorValue = (c.R * 65536) + (c.G * 256) + c.B;
    string ColorHex = string.Format("0x{0:X6}", ColorValue);

Upvotes: 1

Related Questions