Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you convert a floating-point number to its IEEE754 hexadecimal string in PHP?

I am thinking about rewriting my Arithmetic Expression Compiler from JavaScript into PHP, so that it can also be used in browsers which don’t support JavaScript. One quirky problem is that GNU Assembler doesn’t support converting floating-point numbers to IEEE754 hexadecimals, but relies on compilers to do it. Here is how I did that in JavaScript:

        getIEEE754 = function (decimalNumber) {
          var floatArray = new Float32Array([decimalNumber]);
          var buffer = floatArray.buffer;
          var intArray = new Int32Array(buffer);
          return (
            (highlight ? '<span style="color:#007700">' : "") +
            "0x" +
            intArray[0].toString(16) +
            (highlight ? "<\/span>" : "")
          );
        };

So, how do you do that in PHP?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use pack to convert the float to a binary string. Use unpack to convert the binary string to an integer. Use dechex to convert the integer to hex representation.

function getIEEE754($decimalNumber) {
    return '0x' . dechex(unpack('L', pack('f', $decimalNumber))[1]);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading