Skip to content

Instantly share code, notes, and snippets.

@eusonlito
Last active December 5, 2021 14:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eusonlito/cba3071aa49e57b0cf27b9e140f148b1 to your computer and use it in GitHub Desktop.
Save eusonlito/cba3071aa49e57b0cf27b9e140f148b1 to your computer and use it in GitHub Desktop.
Convert a HEXADECIMAL value into a FLOAT
<?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);
}
<?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);
}
<?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