Sign in to follow this  

[web] JavaScript - Short RGB to HEX function

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

If you intended to correct an error in the post then please contact us.

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[i] & 0xF0) >> 4; //Four-bit value, 0-15
  _code[i]+=_hex[_fbit];
  _fbit=_color[i] & 0x0F;
  _code[i]+=_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 this post


Link to post
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.

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this