Monday, June 25, 2012

Viewing Hexdec Results as Standard, Non-Scientific Digits in PHP

When given large numbers, the hexdec function automatically converts the value to scientific notation.  So, "aa1233123124121241" as a hexadecimal value will be converted to "3.13725790445E+21".  If you're converting a hexadecimal value that represents a hash value (md5 or sha), then you need every single bit of that representation to make it useful.  By using the number_format function, you can do that perfectly.  For example :

<?php

            // Author: holdoffhunger@gmail.com
   
        // Example Hexadecimal
        // ---------------------------------------------

    $hexadecimal_string = "1234567890abcdef1234567890abcdef";
   
        // Converted to Decimal
        // ---------------------------------------------

    $decimal_result = hexdec($hexadecimal_string);
   
        // Print Pre-Formatted Results
        // ---------------------------------------------

    print($decimal_result);

            // Output Here: "2.41978572002E+37"
            // .....................................
   
        // Format Results to View Whole All Digits in Integer
        // ---------------------------------------------

            // ( Note: All fractional value of the
            //         Hexadecimal variable are ignored
            //         in the conversion. )
                   
    $current_hashing_algorithm_decimal_result = number_format($decimal_result, 0, '', '');
   
        // Print Formatted Results
        // ---------------------------------------------

    print($current_hashing_algorithm_decimal_result);

            // Output Here: "24197857200151253041252346215207534592"
            // .....................................

?>

Official Function Page: http://php.net/manual/en/function.hexdec.php

// Note: All code appearing on the PHP Revolution blog by the blog owner is released under the Hacktivismo Enhanced-Source Software License Agreement (HESSLA), unless otherwise noted.  http://www.hacktivismo.com/about/hessla.php

No comments:

Post a Comment