Last active
December 5, 2021 14:42
-
-
Save eusonlito/cba3071aa49e57b0cf27b9e140f148b1 to your computer and use it in GitHub Desktop.
Convert a HEXADECIMAL value into a FLOAT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types=1); | |
/** | |
* @param float $value | |
* | |
* @return string | |
*/ | |
function float2hex(float $value): string | |
{ | |
$pack = pack('f', $value); | |
$hex = ''; | |
for ($i = strlen($pack) - 1; $i >= 0; --$i) { | |
$hex .= str_pad(dechex(ord($pack[$i])), 2, '0', STR_PAD_LEFT); | |
} | |
return strtoupper($hex); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types=1); | |
/** | |
* @param string $hex | |
* | |
* @return float | |
*/ | |
function hexfloat(string $hex): float | |
{ | |
$dec = hexdec($hex); | |
if ($dec === 0) { | |
return 0; | |
} | |
$sup = 1 << 23; | |
$x = ($dec & ($sup - 1)) + $sup * ($dec >> 31 | 1); | |
$exp = ($dec >> 23 & 0xFF) - 127; | |
$sign = ($dec & 0x80000000) ? -1 : 1; | |
return $sign * $x * pow(2, $exp - 23); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types=1); | |
/** | |
* @param float $min | |
* @param float $max | |
* @param int $decimals = 6 | |
* | |
* @return float | |
*/ | |
function rand_float(float $min, float $max, int $decimals = 6): float | |
{ | |
$decimals = intval('1'.str_repeat('0', $decimals)); | |
return mt_rand(intval($min * $decimals), intval($max * $decimals)) / $decimals; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment