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?
>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]);
}