Connecting Tech Pros Worldwide Help | Site Map

Function to convert decimal color number into HTML hex color string

Akatz712's Avatar
Newbie
 
Join Date: Apr 2007
Location: New Jersey USA
Posts: 10
#1   Apr 22 '07
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".

Expand|Select|Wrap|Line Numbers
  1. function decimalColorToHTMLcolor(number) {
  2.     //converts to a integer
  3.     var intnumber = number - 0;
  4.  
  5.     // isolate the colors - really not necessary
  6.     var red, green, blue;
  7.  
  8.     // needed since toString does not zero fill on left
  9.     var template = "#000000";
  10.  
  11.     // in the MS Windows world RGB colors
  12.     // are 0xBBGGRR because of the way Intel chips store bytes
  13.     red = (intnumber&0x0000ff) << 16;
  14.     green = intnumber&0x00ff00;
  15.     blue = (intnumber&0xff0000) >>> 16;
  16.  
  17.     // mask out each color and reverse the order
  18.     intnumber = red|green|blue;
  19.  
  20.     // toString converts a number to a hexstring
  21.     var HTMLcolor = intnumber.toString(16);
  22.  
  23.     //template adds # for standard HTML #RRGGBB
  24.     HTMLcolor = template.substring(0,7 - HTMLcolor.length) + HTMLcolor;
  25.  
  26.     return HTMLcolor;
  27.  

Last edited by gits; Nov 13 '07 at 08:24 PM. Reason: added code tags & make code readable



Reply


Similar JavaScript / Ajax / DHTML bytes