Reputation: 105
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?
Upvotes: 1
Views: 2843
Reputation: 69
32 bit binary value is 11111111111111111111111111111111 and convert to decimal which is 4294967295. Then, Do XOR between input value and 4294967295.
function flippingBits($n) {
return $n ^ 4294967295;
}
$result = flippingBits(3);//any input
echo( $result . "\n");
Upvotes: 2
Reputation: 72226
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'
}
Upvotes: 3
Reputation: 1129
You can try out that code
<?php
$bin = sprintf( "%032d", decbin( 0 ));
$out = "";
for( $i = 0; $i < strlen($bin); $i++ ) {
$char = substr( $bin, $i, 1 );
$out .= ($char == 1 ) ? 0 : 1;
}
$dec = bindec($out);
print($out."\n");
print($dec);
?>
Upvotes: 0
Reputation: 9323
Create a mask with bindec(str_repeat("1", 32))
and apply the flip operator ^
decbin(2147483648^bindec(str_repeat("1", 32))) # "1111111111111111111111111111111"
For the integers with lower values, if you need them to get converted as 32 bit integers, you can use sprintf
sprintf('%032d', 1) # "00000000000000000000000000000001"
decbin(sprintf('%032d', 1)^bindec(str_repeat("1", 32))) # "11111111111111111111111111111110"
Upvotes: 0