Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Changed Hex2Color algorithm

I'm not sure that this is the most optimal Hex2Dec2Color code around, but it will do me for the time being. I ended up writing a tool to wrap that following function so that I could easily enter a Hex string and see the color representation of it.

    Dim c As Color = Color.FromArgb( _
            ByteFromHexString("#88A8B2", 0), _
            ByteFromHexString("#88A8B2", 2), _
            ByteFromHexString("#88A8B2", 4) _
        )


    Private Function ByteFromHexString(ByVal hexStrng As String, ByVal rgb As Byte) As Byte
        If Microsoft.VisualBasic.Left(hexStrng, 1) = "#" Then
            hexStrng = Mid(hexStrng, 2)
        End If
        hexStrng = UCase(hexStrng)

        Dim _hex As String = "0123456789ABCDEF"
        Dim iOut As Byte
        Try
            iOut = CByte((_hex.IndexOf(hexStrng.Chars(rgb + 1)) * 16))
            iOut += CByte((_hex.IndexOf(hexStrng.Chars(rgb))))
        Catch ex As System.OverflowException
        Catch ex As System.IndexOutOfRangeException
            ' bad formatted hexstring
        End Try
        Return iOut
    End Function
I must admit that I was amazed that I couldn't find a Hex2Dec method in the BCL though!


3 Comments

  • Er...Byte.Parse()?





    A simple example (in C#, without error-checking):





    using System;


    using System.Drawing;


    using System.Globalization;





    class Test


    {


    static void Main()


    {


    string hexString = "#88A8B2";


    Color color = ConvertHexStringToColor(hexString);


    Console.WriteLine(color);


    }





    static Color ConvertHexStringToColor(string hexString)


    {


    Int32 colorValue = Int32.Parse(hexString.Substring(1), NumberStyles.AllowHexSpecifier);





    return Color.FromArgb(colorValue);


    }


    }





    Jim




  • Oops, Int32.Parse of course, not Byte...





    Remember that the Alpha channel of a color constructed from this will default to 0.





    Also, the reason there isn't a built-in method to do this is probably because '#' isn't the standard way to denote prefix numbers ('0x' is more common).





    Jim

  • Or even Microsoft.VisualBasic.Hex("123")

Comments have been disabled for this content.