From f4cfb30c6afb319113e121618afef6bc32153410 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Roland=20H=C3=A4der?= Date: Mon, 4 Apr 2011 22:19:12 +0000 Subject: [PATCH] Added methods dec2hex()/hex2dec() which are based on user comments at php.net documentation website --- .../main/class_BaseFrameworkSystem.php | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/inc/classes/main/class_BaseFrameworkSystem.php b/inc/classes/main/class_BaseFrameworkSystem.php index d092ccbf..7f871069 100644 --- a/inc/classes/main/class_BaseFrameworkSystem.php +++ b/inc/classes/main/class_BaseFrameworkSystem.php @@ -1551,6 +1551,107 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface { public function getPackageData () { return $this->packageData; } + + /** + * Converts a hexadecimal string, even with negative sign as first string to + * a decimal number using BC functions. + * + * This work is based on comment #86673 on php.net documentation page at: + * + * + * @param $hex Hexadecimal string + * @return $dec Decimal number + */ + function hex2dec ($hex) { + // Convert to all lower-case + $hex = strtolower($hex); + + // Hexadecimal->Decimal translation array + $hexdec = array( + '0' => 0, + '1' => 1, + '2' => 2, + '3' => 3, + '4' => 4, + '5' => 5, + '6' => 6, + '7' => 7, + '8' => 8, + '9' => 9, + 'a' => 10, + 'b' => 11, + 'c' => 12, + 'd' => 13, + 'e' => 14, + 'f' => 15 + ); + + // Detect sign (negative/positive numbers) + $sign = ''; + if (substr($hex, 0, 1) == '-') { + $sign = '-'; + $hex = substr($hex, 1); + } // END - if + + // Decode the hexadecimal string into a decimal number + $dec = 0; + for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) { + $factor = $hexdec[substr($hex, $i, 1)]; + $dec = bcadd($dec, bcmul($factor, $e)); + } // END - for + + // Return the decimal number + return $sign . $dec; + } + + /** + * Converts even very large decimal numbers, also with negative sign, to a + * hexadecimal string. + * + * This work is based on comment #97756 on php.net documentation page at: + * + * + * @param $dec Decimal number, even with negative sign + * @return $hex Hexadecimal string + */ + function dec2hex ($dec) { + // Detect sign (negative/positive numbers) + $sign = ''; + if ($dec < 0) { + $sign = '-'; + $dec = abs($dec); + } // END - if + + // Decimal->hexadecimal translation array + $hexAlphabet = array( + 0 => '0', + 1 => '1', + 2 => '2', + 3 => '3', + 4 => '4', + 5 => '5', + 6 => '6', + 7 => '7', + 8 => '8', + 9 => '9', + 10 => 'a', + 11 => 'b', + 12 => 'c', + 13 => 'd', + 14 => 'e', + 15 => 'f' + ); + + // Encode the decimal number into a hexadecimal string + $hex = ''; + do { + $hex = $hexAlphabet[($dec % 16)] . $hex; + $dec /= 16; + } while( $dec >= 1 ); + + // Return the hexadecimal string + return $sign . $hex; + } } // [EOF] -- 2.30.2