strange issue with PHP

32 views Asked by At

I have been testing the bitwise operators in PHP and encountered a very strange issue. The following program

<?php

  $foon = b'11111111';

  for ($i = 0; $i <= 7 ; $i++) {
    $foo = (($foon & (1 << $i)) > 0) ? 1 : 0;
    echo "bit " . $i . " of target is " . $foo . "<br />" . PHP_EOL;
  }

should produce the output

bit 0 of target is 1
bit 1 of target is 1
bit 2 of target is 1
bit 3 of target is 1
bit 4 of target is 1
bit 5 of target is 1
bit 6 of target is 1
bit 7 of target is 1

However, the actual output is

bit 0 of target is 1
bit 1 of target is 1
bit 2 of target is 1
bit 3 of target is 0
bit 4 of target is 0
bit 5 of target is 0
bit 6 of target is 1
bit 7 of target is 1

Is there something painfully obvious that I failed to see, or is that a bug in PHP? I am using PHP version 8.2.4 through XAMPP. Thank you very much.

1

There are 1 answers

1
fat penguin On

Nevermind, I figured it out. b'11111111' isn't actually a binary representation of number in PHP, athough it doesn't complain. Assigning 0b11111111 to my variable produces the correct answer.