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

标签 php floating-point numerical-methods

有没有办法在 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/

相关文章:

javascript - JS用什么技巧显示/计算 float

python - 数字代码回归测试框架

c++ - C++ 库中的快速梯度下降实现?

php文件加密方法。简单的东西存在吗?

javascript - 可以在 Laravel 中编码并在 JavaScript 中解码的 JWT

php - 连接表时字段列表中的列不明确 codeigniter

PHP字符串 float

python - 如何设置一个具有所有方法和功能的类,如内置的 float,但保留额外的数据?

c - 将 regula falsi 方法修改为割线方法

php - 如何制作json api