note 108739 modified in function.dechex by danbrown
| From: | danbrown@php.net | Date: | Tue, 22 May 2012 14:34:07 +0000 |
| Subject: | note 108739 modified in function.dechex by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-188132@lists.php.net to get a copy of this message | ||
For those who are looking for a function to calculate the hex of ANY length integer, here is my
snippet: <?php // The function to
convert any length integers to hex // Input: Decimal string //
Output: Hex string function
dec2hex($str) { 	$hex =
array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'); 	//
Result value 	$hexval = ''; 	// The
quotient of each division operation 	$quotient =
$str; 	$divisor =
$str; 	 	while($quotient >
15) 	{ 		$len =
strlen($divisor); 		$pos =
1; 		$quotient = 0; 		// Take the
first two digits as temp divisor and advance by 1 each
iteration 		$div = substr($divisor, 0,
2); 		$remainder =
$div[0]; 		while($pos <
$len) 		{ 			$div =
intval($remainder.$divisor[$pos]); 			$remainder = $div %
16; 			$quotient =
intval($quotient.floor($div/16)); 			$pos++; 		} 		//
Recast the divisor as string to make the $divisor[$pos]
work 		$divisor =
"$quotient"; 		$hexval =
$hex[$remainder].$hexval; 	} 	$hexval =
$hex[$quotient].$hexval; 	return
$hexval; } ?>
--was--
For those who are looking for a function to calculate the hex of ANY length integer, here is my
snippet:
// The function to convert any length integers to hex
// Input: Decimal string
// Output: Hex string
function dec2hex($str)
{
$hex =
array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
// Result value
$hexval = '';
// The quotient of each division operation
$quotient = $str;
$divisor = $str;
while($quotient > 15)
{
$len = strlen($divisor);
$pos = 1;
$quotient = 0;
// Take the first two digits as temp divisor and advance by 1 each iteration
$div = substr($divisor, 0, 2);
$remainder = $div[0];
while($pos < $len)
{
$div = intval($remainder.$divisor[$pos]);
$remainder = $div % 16;
$quotient = intval($quotient.floor($div/16));
$pos++;
}
// Recast the divisor as string to make the $divisor[$pos] work
$divisor = "$quotient";
$hexval = $hex[$remainder].$hexval;
}
$hexval = $hex[$quotient].$hexval;
return $hexval;
}
http://php.net/manual/en/function.dechex.php