PHP Program to Reverse Bit of a Number
Last Updated :
24 Apr, 2024
Improve
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
Approach 1: 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
Approach 2: Reverse Bit of a Number using PHP Functions
The PHP function reverseBits($number) takes an integer as input, converts it to its binary representation, reverses the binary string, and then converts it back to an integer.
- Convert the input number to its binary representation using decbin($number). This gives us a binary string.
- Convert the binary string to a regular string using strval($binary).
- Reverse the string using strrev($binString) to get the reversed binary string.
- Convert the reversed binary string back to an integer using bindec($revBin).
<?php
function reverseBits($number) {
$binary = decbin($number);
echo $binary . "\n";
$binString = strval($binary);
$revBin = strrev($binString);
$revNum = bindec($revBin);
// Required number
return $revNum;
}
// Driver Code
$number = 11;
$reversedNumber = reverseBits($number);
echo "Reversed Number: $reversedNumber";
?>
Output
1011 Reversed Number: 13