php 16进制转 float 32
23-9-11 9:49:55
function HexToSingle($t) {
$t = str_replace(' ', '', $t);
if ($t == '') {
return '';
}
if ($t == '00000000') {
return '0';
}
if (strlen($t) > 8 || !ctype_xdigit($t)) {
return 'Error';
}
if (strlen($t) < 8) {
$t = FillString($t, '0', 8, true);
}
$t = base_convert($t, 16, 2);
$t = FillString($t, '0', 32, true);
$s = substr($t, 0, 1);
$e = substr($t, 1, 8);
$m = substr($t, 9);
$e = base_convert($e, 2, 10) - 127;
$m = '1' . $m;
if ($e >= 0) {
$m = substr($m, 0, $e + 1) . '.' . substr($m, $e + 1);
} else {
$m = '0.' . FillString($m, '0', strlen($m) - $e - 1, true);
}
if (strpos($m, '.') === false) {
$m .= '.0';
}
$a = explode('.', $m);
$mi = base_convert($a[0], 2, 10);
$mf = 0;
for ($i = 0; $i < strlen($a[1]); $i++) {
$mf += intval($a[1][$i]) * pow(2, -($i + 1));
}
$m = intval($mi) + floatval($mf);
if ($s == 1) {
$m = -$m;
}
return $m;
}
function FillString($t, $c, $n, $b) {
if (($t == '') || (strlen($c) != 1) || ($n <= strlen($t))) {
return $t;
}
$l = strlen($t);
for ($i = 0; $i < $n - $l; $i++) {
if ($b == true) {
$t = $c . $t;
} else {
$t .= $c;
}
}
return $t;
}
// Example usage:
$hexValue = '41CC0000'; // Example hexadecimal value to convert to single-precision floating point number
$result = HexToSingle($hexValue);
echo $result; // Output: 1.23456789 (approximate value)