Search code examples
phpbit-manipulation

Flipping bits in PHP


Ok, the problem is : You will be given a list of 32-bits unsigned integers in a file to read. You are required to output the list of the unsigned integers you get by flipping bits in its binary representation (i.e. unset bits must be set, and set bits must be unset).

The Sample input is:

3
2147483647
1
0

And the sample output is:

2147483648
4294967294
4294967295

Where the 3 in the input is the number of lines.

<?php

$_fp = fopen("php://stdin", "r");
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
$t = fgets($_fp);


for($i=0;$i<$t;$i++){
    $line = fgets($_fp);
    $binLine = decbin($line);
    $reverse = strrev($binLine);
    echo bindec($reverse)."\n";
}

fclose($_fp);
?>

How is this wrong? And should I be using bitwise operators instead?


Solution

  • You said "unset bits must be set, and set bits must be unset". This is the result of XOR-ing every bit of each number with 1.

    The code should read:

    for($i=0;$i<$t;$i++){
        $line = fgets($_fp);
        echo(($line ^ 0xFFFFFFFF)."\n");       # 32-bit full of '1'
    }