0

I need to check which hexadecimal flags are included in a certain decimal variable. At the moment the script just works for small decimals but I've some longer ones.

In the following example it shows me the right flags when I check the flags inside $decimal2, but it doesn't work with $decimal.

I don't know the reason for this behaviour and what has to be changed.

This is the 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);
Berstos
  • 179
  • 10

1 Answers1

2

First of all, none of the flags are set in your $decimal so it is expected to print nothing. Even if you did set those flags, let say by adding 0xfff to $decimal, it still won't print anything because the number is too large to be stored as an int, so it is stored as a float, which has limited precision. You can see this with var_dump()

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

Output:

float(6.13090029426844E+32)
int(64)

A floating point number only stores the most significant digits (roughly 14 digits), any digit in the lower significant places are inevitably discarded.

$decimal3 = 613090029426844e18 + 0xfff;

Output:

float(6.13090029426844E+32)

So you won't be able to use the lower significant digits in a large number. You may want to take a look at BigInterger class Is there a BigInteger class in PHP?

Ricky Mo
  • 6,285
  • 1
  • 14
  • 30
  • Do I understand it the right way... If I use a biginteger class the above code would work because it's an integer and not a float anymore? – Berstos Aug 19 '21 at 02:17
  • Yes. You have to refractor your code to use the dedicated BigInteger methods. – Ricky Mo Aug 19 '21 at 02:54