note 87702 deleted from function.dechex by danbrown
| From: | danbrown@php.net | Date: | Thu, 18 Dec 2008 14:46:43 +0000 |
| Subject: | note 87702 deleted from function.dechex by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-148316@lists.php.net to get a copy of this message | ||
Note Submitter: mandor at mandor dot net
Reason: integrated
----
Here's a simple function that converts signed decimal numbers to hexadecimal strings. It can
handle numbers virtually as big as you want and you can optionally set a number of digits for the
result which will then be padded appropriately.
<?php
function dec2hex($dec, $digits=false) {
// If the decimal number is negative, we'll have to invert the result in the end.
$invert = $dec < 0 ? true : false;
$hex = '';
while($dec) {
// Calculates the modulus, converts it to hex and adds it to the result.
$hex .= dechex(abs(bcmod($dec, '16')));
// Divises the decimal number by 16 and loop.
$dec = bcdiv($dec, '16', 0);
}
// Adds some padding to get the required number of digits if needed.
if ($digits) {
while (strlen($hex) < $digits) { $hex .= '0'; }
}
// Inverts the result if the decimal number was negative.
if ($invert) {
for ($i = 0; $i < strlen($hex); $i++) {
$hex[$i] = dechex(($i ? 15 : 16) - hexdec($hex[$i]));
}
}
// Returns the result (it needs to be reversed because of the way it was computed).
return strrev($hex);
}
?>