• Advertisement

Archived

This topic is now archived and is closed to further replies.

A RGB() function to return in hex

This topic is 5103 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

Hi all, I am currently coding a RGB() function for PHP. Basicially, the idea is that if you put in RGB(255, 255, 255) you will get the hexdemical #FFFFFF. What''s a good way to do this? Thanks in advance.

Share this post


Link to post
Share on other sites
Advertisement
In C++


int rgb(int r, int g, int b)
{
return (r<<16) + (g<<8) + b;
}


If PHP doesn't have the << operator, use

int rgb(int r, int g, int b)
{
return (r*65536) + (g*256) + b;
}


This gives it to you in numeric form, that's how I interpreted the question, if you want it in string form it should be a simple matter of converting each number->hex->string then combining the strings.

[edited by - cozman on March 7, 2004 1:01:20 AM]

Share this post


Link to post
Share on other sites
PHP has a build-in function to convert decimals to hex. So the following functions should solve your problem:
function rgbToHex ($r, $g, $b) 
{
$hex = array();

if (strlen($hex[0] = dechex($r)) == 1)
$hex[0] = '0'.$hex

if (strlen($hex[1] = dechex($g)) == 1)
$hex[1] = '0'.$hex

if (strlen($hex[2] = dechex($b)) == 1)
$hex[2] = '0'.$hex

return $hex;
}

Edit: The function returns an array now.

- Gom Jabbar

[edited by - Gom Jabbar on March 7, 2004 9:13:55 AM]

Share this post


Link to post
Share on other sites

  • Advertisement