note 108739 modified in function.dechex by danbrown

From: 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:&#13;&#10;&#13;&#10;&#60;?php&#13;&#10;// The function to convert any length integers to hex&#13;&#10;// Input: Decimal string&#13;&#10;// Output: Hex string&#13;&#10;function dec2hex($str)&#13;&#10;{&#13;&#10;&#9;$hex = array(&#39;0&#39;,&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;4&#39;,&#39;5&#39;,&#39;6&#39;,&#39;7&#39;,&#39;8&#39;,&#39;9&#39;,&#39;A&#39;,&#39;B&#39;,&#39;C&#39;,&#39;D&#39;,&#39;E&#39;,&#39;F&#39;);&#13;&#10;&#9;// Result value&#13;&#10;&#9;$hexval = &#39;&#39;;&#13;&#10;&#9;// The quotient of each division operation&#13;&#10;&#9;$quotient = $str;&#13;&#10;&#9;$divisor = $str;&#13;&#10;&#9;&#13;&#10;&#9;while($quotient &#62; 15)&#13;&#10;&#9;{&#13;&#10;&#9;&#9;$len = strlen($divisor);&#13;&#10;&#9;&#9;$pos = 1;&#13;&#10;&#9;&#9;$quotient = 0;&#13;&#10;&#9;&#9;// Take the first two digits as temp divisor and advance by 1 each iteration&#13;&#10;&#9;&#9;$div = substr($divisor, 0, 2);&#13;&#10;&#9;&#9;$remainder = $div[0];&#13;&#10;&#9;&#9;while($pos &#60; $len)&#13;&#10;&#9;&#9;{&#13;&#10;&#9;&#9;&#9;$div = intval($remainder.$divisor[$pos]);&#13;&#10;&#9;&#9;&#9;$remainder = $div % 16;&#13;&#10;&#9;&#9;&#9;$quotient = intval($quotient.floor($div/16));&#13;&#10;&#9;&#9;&#9;$pos++;&#13;&#10;&#9;&#9;}&#13;&#10;&#9;&#9;// Recast the divisor as string to make the $divisor[$pos] work&#13;&#10;&#9;&#9;$divisor = &#34;$quotient&#34;;&#13;&#10;&#9;&#9;$hexval = $hex[$remainder].$hexval;&#13;&#10;&#9;}&#13;&#10;&#9;$hexval = $hex[$quotient].$hexval;&#13;&#10;&#9;return $hexval;&#13;&#10;}&#13;&#10;?&#62; --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

« previous php.notes (#188132) next »