note 108739 deleted from function.dechex by danbrown
| From: | danbrown@php.net | Date: | Fri, 25 May 2012 15:24:06 +0000 |
| Subject: | note 108739 deleted from function.dechex by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-188238@lists.php.net to get a copy of this message | ||
Note Submitter: huangwen77 at gmail dot com
----
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;
}
?>