#### Archived

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

# A RGB() function to return in hex

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

## 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 on other sites
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 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]

1. 1
Rutin
34
2. 2
3. 3
4. 4
5. 5

• 12
• 14
• 9
• 9
• 9
• ### Forum Statistics

• Total Topics
633333
• Total Posts
3011404
• ### Who's Online (See full list)

There are no registered users currently online

×