Convert a hex string into a 32-bit IEEE 754 float number in PHP

By: Julian L  

Convert a hex string into a 32-bit IEEE 754 float number. This function is 2 times faster then the below hex to 32bit function. This function only changes datatypes (string to int) once. Also, this function is a port from the hex to 64bit function from below.

<?php
function hexTo32Float($strHex) {
    $v = hexdec($strHex);
    $x = ($v & ((1 << 23) - 1)) + (1 << 23) * ($v >> 31 | 1);
    $exp = ($v >> 23 & 0xFF) - 127;
    return $x * pow(2, $exp - 23);
}
?>

<?php
//example
echo hexTo32Float("C4028000"); // outputs: -522
echo hexTo32Float("457F9000"); // outputs: 4089
echo hexTo32Float("2D7F5");    // outputs: 6.00804264307E-39
echo hexTo32Float("0002D7F5"); // outputs: 6.00804264307E-39
echo hexTo32Float("47D9F95E"); // outputs: 111602.734375
?>



Archived Comments

1. Jaspertip
View Tutorial          By: Jaspertip at 2017-07-18 09:14:57

2. My code:

$hex=array('C4028000','457F9000','2D7F5','0002D7F5','47D9F95E','000040E4');<

View Tutorial          By: Mark at 2015-02-02 14:42:56


Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial