# [web] JavaScript - Short RGB to HEX function

This topic is 4771 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I've just made a simple function for RGB to HEX conversion, and since I have nothing else to do, I'll go ahead and post it. I'm doing it mainly because I've seen some of the other ones, and they can take up to 50 lines. This one takes up around 12.
function toHex(_red,_green,_blue) {
var _hex=new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
var _color=new Array(_red,_green,_blue);
var _code=new Array("","","");
for (i=0;i<3;i++) {
//High bit, low bit
_fbit=(_color & 0xF0) >> 4; //Four-bit value, 0-15
_code+=_hex[_fbit];
_fbit=_color & 0x0F;
_code+=_hex[_fbit];
}
return _code[0]+_code[1]+_code[2];
}
There are probably some other ways to make it small, but I can't think of any right now...

##### Share on other sites
This should work in most recent browsers:

function toHex(_red,_green,_blue) { return ((_red & 0xF0) >> 4).toString(16) +        (_red & 0x0F).toString(16) +        ((_green & 0xF0) >> 4).toString(16) +        (_green & 0x0F).toString(16) +        ((_blue & 0xF0) >> 4).toString(16) +        (_blue & 0x0F).toString(16);}

Unfortunately the toString function doesn't seem to allow you to add leading zeroes so you have to do it one hex digit at a time.

1. 1
Rutin
24
2. 2
3. 3
JoeJ
18
4. 4
5. 5

• 38
• 23
• 13
• 13
• 17
• ### Forum Statistics

• Total Topics
631706
• Total Posts
3001835
×