Search code examples
vbscriptasp-classichexrgb

Convert Hex to RGB in ASP Classic


Can you please advise me on how to convert hex to RGB in ASP Classic/VBScript. I have tried to search all over the Internet and tried out many suggested solutions but none point to what I want to achieve.

I have tried the following functions but none of them work: Convert hex color string to RGB color

After converting to RBB, I wish to set the text color based on the background color. So basically my background color code is in hex.


Solution

  • First, you convert your hex code into decimal using "&h" representation and parsing the result. After that, it's a matter of doing basic bitwise operators to extract the RGB values from the number.

    Dim hexval : hexval = "fdfeff"
    
    Dim rgbval : rgbval = CLng("&h" & hexval)
    Dim r : r = (rgbval And &hff0000&) / 65536
    Dim g : g = (rgbval And &h00ff00&) / 256
    Dim b : b = (rgbval And &h0000ff&)
    
    wscript.echo Join(Array(hexval, rgbval, r, g, b), vbcrlf)
    

    This produces the following output:

    fefeff
    16645887
    253
    254
    255