gpt4 book ai didi

php - 如何在 PHP 中获取 float 的二进制表示?

转载 作者:可可西里 更新时间:2023-11-01 12:51:56 24 4
gpt4 key购买 nike

有没有办法在 PHP 中获取 float 的二进制表示?类似于 Java 的 Double.doubleToRawLongBits() .

给定一个正 float ,我想得到小于该数的最大可表示 float 。在 Java 中,我可以这样做:

double x = Double.longBitsToDouble(Double.doubleToRawLongBits(d) - 1);

但是我在 PHP 中没有看到任何类似的东西。

最佳答案

这是我使用 Peter Bailey 想出的解决方案的建议。它需要 64 位版本的 PHP。我不以任何方式声称这是生产质量,但我分享以防万一有人想以此为基础。 (事实上​​ ,在我发布问题后我最终做了一些完全不同的事情,但我把它留在这里作为一个智力练习。)

// Returns the largest double-precision floating-point number which
// is less than the given value. Only works for positive values.
// Requires integers to be represented internally with 64 bits (on Linux
// this usually means you're on 64-bit OS with PHP built for 64-bit OS).
// Also requires 64-bit double-precision floating point numbers, but I
// think this is the case pretty much everywhere.
// Returns false on error.
function prevDouble($d) {
$INT32_MASK = 0xffffffff;
if((0x1deadbeef >> 32) !== 1) {
echo 'error: only works on 64-bit systems!';
return false;
}
if($d <= 0) {
return false;
}
$beTest = bin2hex(pack('d', 1.0)); //test for big-endian
if(strlen($beTest) != 16) {
echo 'error: system does not use 8 bytes for double precision!';
return false;
}

if($beTest == '3ff0000000000000') {
$isBE = true;
}
else if($beTest == '000000000000f03f') {
$isBE = false;
}
else {
echo 'error: could not determine endian mode!';
return false;
}

$bin = pack('d', $d);

//convert to 64-bit int
$int = 0;
for($i = 0; $i < 8; $i++)
$int = ($int << 8) | ord($bin[$isBE ? $i : 7 - $i]);

$int--;
//convert back to double
if($isBE)
$out = unpack('d', pack('N', ($int >> 32) & $INT32_MASK) . pack('N', $int & $INT32_MASK));
else
$out = unpack('d', pack('V', $int & $INT32_MASK) . pack('V', ($int >> 32) & $INT32_MASK));

return $out[1];
}

关于php - 如何在 PHP 中获取 float 的二进制表示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4729526/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com