0

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.

  • [What does the b in front of string literals do?](https://stackoverflow.com/questions/4749442/what-does-the-b-in-front-of-string-literals-do) – Álvaro González Jun 27 '23 at 07:09

1 Answers1

1

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.

  • It's a hint that it's a binary string (as in "JPEG picture"). But in fact it doesn't do anything because PHP doesn't even have non-binary strings. It's a leftover from a development branch that was abandoned. – Álvaro González Jun 27 '23 at 07:52