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
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