note 83122 modified in function.dechex by danbrown

From: Date: Tue, 16 Feb 2010 23:27:30 +0000
Subject: note 83122 modified in function.dechex by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-166036@lists.php.net to get a copy of this message
I was challenged by a problem with large number calculations and conversion to hex within php. The calculation exceeded unsigned integer and even float range. You can easily change it for your needs but it is, thanks to bcmath, capable of handling big numbers via string. This function will convert them to hex. In this specific example though, since I use it for game internals that can only handle 32 bit numbers, it will truncate calculations at 8 digits. If the input is 1 for example it will be filled up with zeros. Output 00000001h. Of course I don't claim it to be a good one, but it works for me and my purpose. Suggestions on faster code welcome! <?php // Turns numbers into 32-bit hex string; Fills up zeros function lrgDec2Hex($number) { $i = 0; $hex = array(); while($i < 8) { if($number == 0) { array_push($hex, '0'); } else { array_push($hex, strtoupper(dechex(bcmod($number, '16')))); $number = bcdiv($number, '16', 0); } $i++; } krsort($hex); return implode($hex); } ?> --was-- I was challenged by a problem with large number calculations and conversion to hex within php. The calculation exceeded unsigned integer and even float range. You can easily change it for your needs but it is, thanks to bcmath, capable of handling big numbers via string. This function will convert them to hex. In this specific example though, since I use it for game internals that can only handle 32 bit numbers, it will truncate calculations at 8 digits. If the input is 1 for example it will be filled up with zeros. Output 00000001h. Of course I don't claim it to be a good one, but it works for me and my purpose. Suggestions on faster code welcome! // Turns numbers into 32-bit hex string; Fills up zeros function lrgDec2Hex($number) { $i = 0; $hex = array(); while($i < 8) { if($number == 0) { array_push($hex, '0'); } else { array_push($hex, strtoupper(dechex(bcmod($number, '16')))); $number = bcdiv($number, '16', 0); } $i++; } krsort($hex); return implode($hex); } http://php.net/manual/en/function.dechex.php

« previous php.notes (#166036) next »