Jump to content
  • Advertisement
Sign in to follow this  
deadimp

[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.

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 & 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 this post


Link to post
Share on other sites
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!