Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

leading zeroes in hexadecimals 1

Status
Not open for further replies.

MasterKaos

Programmer
Joined
Jan 17, 2004
Messages
107
Location
GB
Ok, i had a very similar question a few days ago about leading zeroes in integers, and it was pointed out that the sprintf() function did this no problems.

But what about hexadecimals? I'm writing a function that takes an array with three integers (one each for red, green, blue) and creates a 6 digit hexadecimal colour code to be used in HTML:

Code:
$colour = array(r=>254, g=>213, b=>0);

...

function tohex($colour)
{
	$output="";
	$output.= dechex($colour[r]);
	$output.= dechex($colour[g]);
	$output.= dechex($colour[b]);
	return $output;
}

but the problem is single digit numbers mess the whole thing up, for example "F0F" won;t work in HTML, it would have to be "0F000F" for HTML.

Any ideas how to do this?

----------------------------------------------------------------------------
The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.
 
function tohex($colour)
{
$output="";
$output.= str_pad(dechex($colour[r]),2,0,STR_PAD_LEFT);
$output.= str_pad(dechex($colour[g]),2,0,STR_PAD_LEFT);
$output.= str_pad(dechex($colour),2,0,STR_PAD_LEFT);
return $output;
}


______________________________________________________________________
There's no present like the time, they say. - Henry's Cat.
 
Thankyou! Works beautifully :-)

----------------------------------------------------------------------------
The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.
 
Don't forget that printf() can solve this problem, too.

This script:
Code:
<?php
$color = array('r' => 254, 'g' => 213, 'b' => 0);

printf ('%02X%02X%02X', $color['r'], $color['g'], $color['b']);
?>

Outputs:

FED500





Want the best answers? Ask the best questions!

TANSTAAFL!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top