Function to convert decimal color number into HTML hex color string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Akatz712
    New Member
    • Apr 2007
    • 9

    Function to convert decimal color number into HTML hex color string

    The following function converts a decimal number representing a color stored in the way that Microsoft windows stores colors (low byte is red), and converts it to a hex string which is needed for web applications, namely "#RRGGBB".

    [CODE=javascript]
    function decimalColorToH TMLcolor(number ) {
    //converts to a integer
    var intnumber = number - 0;

    // isolate the colors - really not necessary
    var red, green, blue;

    // needed since toString does not zero fill on left
    var template = "#000000";

    // in the MS Windows world RGB colors
    // are 0xBBGGRR because of the way Intel chips store bytes
    red = (intnumber&0x00 00ff) << 16;
    green = intnumber&0x00f f00;
    blue = (intnumber&0xff 0000) >>> 16;

    // mask out each color and reverse the order
    intnumber = red|green|blue;

    // toString converts a number to a hexstring
    var HTMLcolor = intnumber.toStr ing(16);

    //template adds # for standard HTML #RRGGBB
    HTMLcolor = template.substr ing(0,7 - HTMLcolor.lengt h) + HTMLcolor;

    return HTMLcolor;
    }
    [/CODE]
    Last edited by gits; Nov 13 '07, 08:24 PM. Reason: added code tags & make code readable
Working...