Convert int to string as hex number

Today I needed to parse colors encoded as string in the form 0xRRGGBB where RR GG and BB were red green and blue values of given color encoded in hexadecimal.

Problem I stumbled upon, was, what if I have a number like:

0x008000

There was no problem converting it to System.Drawing.Color class, but back to string.

I used code like below:

string colorString = string.Format("0x{0:X}{1:X}{2:X}",

                       color.R,

                       color.G,

                       color.B);

This would yield:

0x0800

Which is definitely not what I wanted it to be. I needed a way to enforce a number to emit zero in front of it, if it’s small enough to fit in one digit.

After much too long search, trial and error I found a solution, that was so obvious when I finally discovered it, that I felt like it should be the first thing to try: you just give a number right after ‘X’, indicating how many chars you want the number to have. Considering the fact that I tried ‘X,2’, ‘X:2’, ‘X;2’ ‘X,00’ and several more before I tried this I feel now… well, not very well about myself 😉

string string1 = @"0x008000";

Color color = (Color) new ColorConverter().ConvertFromString(string1);

string colorString = string.Format("0x{0:X2}{1:X2}{2:X2}",

                               color.R,

                               color.G,

                               color.B);

Took me like 30 minutes to figure it out.

  • RobH

    Just what was needed. Thanks for helping scrape a little bit of the rust off.