w3resource

PHP Exercises: Check if the bits of the two given positions of a number are same or not

PHP: Exercise-34 with Solution

Write a PHP program to check if the bits of the two given positions of a number are same or not.

112 - > 01110000
Test 2nd and 3rd position
Result: True
Test 4th and 5th position
Result: False

Sample Solution:

PHP Code:

<?php
// Function to test if bits at two specified positions are equal
function test_bit_position($num, $pos1, $pos2) {
    // Adjust positions to start from 0 (as arrays in PHP are 0-indexed)
    $pos1--;
    $pos2--;
    
    // Convert the decimal number to a binary string and reverse it
    $bin_num = strrev(decbin($num));

    // Check if the bits at the specified positions are equal
    if ($bin_num[$pos1] == $bin_num[$pos2]) {
        return "true";
    } else {
        return "false";
    }
}

// Test case
echo test_bit_position(112, 5, 6) . "\n";

?>

Explanation:

  • Function Definition:
    • The test_bit_position($num, $pos1, $pos2) function checks if the bits at two specified positions in a number's binary representation are equal.
  • Adjust Bit Positions:
    • $pos1-- and $pos2-- adjust the positions to be zero-indexed, as PHP strings are zero-indexed (e.g., position 1 becomes 0).
  • Convert Number to Binary:
    • decbin($num) converts the decimal number $num to a binary string.
    • strrev() reverses the binary string to match the bit positions from right to left, making it easier to access bits by index.
  • Check Equality of Specified Bits:
    • The function checks if the bits at the adjusted positions $pos1 and $pos2 are equal:
      • If they are, it returns "true".
      • If not, it returns "false".
  • Test Case:
    • The function is tested with the number 112 and positions 5 and 6.
    • The result is printed with echo.

Output:

true

Flowchart:

Flowchart: Check if the bits of the two given positions of a number are same or not

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP program to convert word to digit.
Next: Write a PHP program to remove duplicates from a sorted list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/php-basic-exercise-34.php