【问题标题】:Check which flags are included inside a decimal检查小数内包含哪些标志
【发布时间】:2021-10-20 18:07:33
【问题描述】:

我需要检查某个十进制变量中包含哪些十六进制标志。目前该脚本仅适用于小数,但我有一些更长的。

在以下示例中,当我检查 $decimal2 中的标志时,它会显示正确的标志,但它不适用于 $decimal

我不知道这种行为的原因以及需要改变的地方。

这是example demo

$decimal = 613090029426844e18; // doesn't work
$decimal2 = 64; //works

const FLAG_1 = 0x1;
const FLAG_2 = 0x2; 
const FLAG_3 = 0x4;
const FLAG_4 = 0x4;
const FLAG_5 = 0x32;
const FLAG_6 = 0x40;
const FLAG_7 = 0x400;
 
function show_flags ($decimal) {
  if ($decimal & FLAG_1) {
    echo "Flag 1 included.<br>\n";
  }
  if ($decimal & FLAG_2) {
    echo "Flag 2 included.<br>\n";
  }
  if ($decimal & FLAG_3) {
    echo "Flag 3 included.<br>\n";
  }
  if ($decimal & FLAG_4) {
    echo "Flag 3 included.<br>\n";
  }
  if ($decimal & FLAG_5) {
    echo "Flag 3 included.<br>\n";
  }
  if ($decimal & FLAG_6) {
    echo "Flag 3 included.<br>\n";
  }
  if ($decimal & FLAG_7) {
    echo "Flag 3 included.<br>\n";
  }
}

show_flags($decimal);

【问题讨论】:

    标签: php flags bitmask


    【解决方案1】:

    首先,您的$decimal 中没有设置任何标志,因此预计不会打印任何内容。即使您确实设置了这些标志,比如说通过将0xfff 添加到$decimal,它仍然不会打印任何内容,因为该数字太大而无法存储为int,因此将其存储为@987654326 @,其精度有限。你可以通过var_dump()看到这个

    $decimal = 613090029426844e18; // doesn't work
    $decimal2 = 64; //works
    var_dump($decimal);
    var_dump($decimal2);
    

    输出:

    float(6.13090029426844E+32)
    int(64)
    

    浮点数只存储最高有效位(大约 14 位),低位的任何数字都不可避免地被丢弃。

    $decimal3 = 613090029426844e18 + 0xfff;
    

    输出:

    float(6.13090029426844E+32)
    

    因此,您将无法大量使用低位有效数字。你可能想看看BigIntergerIs there a BigInteger class in PHP?

    【讨论】:

    • 我的理解正确吗...如果我使用 biginteger 类,上面的代码可以工作,因为它是整数而不是浮点数了?
    • 是的。您必须重构代码才能使用专用的 BigInteger 方法。
    猜你喜欢
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多