Reverse Bit of a Number using Bitwise Shift Operators
In this approach, we obtain each bit of the binary representation of the number N by using the bitwise right shift operator. We then accumulate these bits in the variable “rev” using the bitwise left shift operation.
<?php
function reverseBits($number) {
$reverse = 0;
while ($number > 0) {
// Bitwise left shift 'rev' by 1
$reverse <<= 1;
// If current bit is '1'
if ($number & 1 == 1)
$reverse ^= 1;
// Bitwise right shift 'n' by 1
$number >>= 1;
}
// Required number
return $reverse;
}
// Driver Code
$number = 11;
$reversedNumber = reverseBits($number);
echo "Reversed Number: $reversedNumber";
?>
Output
Reversed Number: 13
PHP Program to Reverse Bit of a Number
Given a number N, the task is to Reverse the Bit of the number and convert back into a decimal number in PHP.
Examples:
Input: N = 11
Output: 13
Explanations: (11)10 = (1011)2
After revering the Bits (1101)2 = (13)10