note 87702 added to function.dechex

From: Date: Wed, 17 Dec 2008 14:50:24 +0000
Subject: note 87702 added to function.dechex
Groups: php.notes 
Request: Send a blank email to php-notes+get-148265@lists.php.net to get a copy of this message
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); } ?> ---- Server IP: 195.221.21.36 Probable Submitter: 86.221.30.55 ---- Manual Page -- http://www.php.net/manual/en/function.dechex.php Edit -- https://master.php.net/note/edit/87702 Del: integrated -- https://master.php.net/note/delete/87702/integrated Del: useless -- https://master.php.net/note/delete/87702/useless Del: bad code -- https://master.php.net/note/delete/87702/bad+code Del: spam -- https://master.php.net/note/delete/87702/spam Del: non-english -- https://master.php.net/note/delete/87702/non-english Del: in docs -- https://master.php.net/note/delete/87702/in+docs Del: other reasons-- https://master.php.net/note/delete/87702 Reject -- https://master.php.net/note/reject/87702 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#148265) next »