By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,225 Members | 2,172 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Function to convert decimal color number into HTML hex color string

Akatz712
P: 10
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.  
Apr 22 '07 #1
Share this Article
Share on Google+