Nuthin' but .NET

Convert .NET Color to Hex String

Summary

For a long time I had a fairly complicated way of converting the .NET Color object to a string such as #F782AB. Since then some of you have informed me of a much easier way. I'll show you the easy way first and then include the longer method below.

Color c = Color.Red;
string strColor = System.Drawing.ColorTranslator.ToHtml(c);

Pretty simple isn't it. Don't you just love these little .NET niceties that you can never find when you want 'em?

So before I figured that out, it worked something like this. Note that lblOutput is a Label control on my ASP.NET page.

Example: How to use the conversion method
public void TestColorToHexString()
{
   Color c1 = Color.White;
   Color c2 = Color.Black;
   Color c3 = Color.LightGoldenrodYellow;
   Color c4 = Color.Gold;

   lblOutput.Text = c1.Name + " =  " 
      + Snippets00002.ColorToHexString(c1) + "<br>";
   lblOutput.Text += c2.Name + " =  " 
      + Snippets00002.ColorToHexString(c2) + "<br>";
   lblOutput.Text += c3.Name + " =  " 
      + Snippets00002.ColorToHexString(c3) + "<br>";
   lblOutput.Text += c4.Name + " =  " 
      + Snippets00002.ColorToHexString(c4) + "<br>";

}

If you run the previous method you'll get the following output displayed in the Label control on the aspx page.

Example: Output
White = FFFFFF
Black = 000000
LightGoldenrodYellow = FAFAD2
Gold = FFD700

Here's the class:

The C# Class:
namespace Cambia.CoreLib
{
   using System;
   using System.Drawing;

   /// <summary>
   /// Useful C# snippets from CambiaResearch.com
   /// </summary>
   public class Snippets00002
   {
      #region -- Data Members --
      static char[] hexDigits = {
         '0', '1', '2', '3', '4', '5', '6', '7',
         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
      #endregion

      public Snippets00002()
      {
      }

      /// <summary>
      /// Convert a .NET Color to a hex string.
      /// </summary>
      /// <returns>ex: "FFFFFF", "AB12E9"</returns>
      public static string ColorToHexString(Color color) 
      {
         byte[] bytes = new byte[3];
         bytes[0] = color.R;
         bytes[1] = color.G;
         bytes[2] = color.B;
         char[] chars = new char[bytes.Length * 2];
         for (int i = 0; i < bytes.Length; i++) 
         {
            int b = bytes[i];
            chars[i * 2] = hexDigits[b >> 4];
            chars[i * 2 + 1] = hexDigits[b & 0xF];
         }
         return new string(chars);
      }


   }
}
 

Version: 6.0.20200920.1535