Open In App

Octal to Binary Converter in PHP

Last Updated : 16 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Converting an octal number to a binary number is a common task in programming.

Note:

  • Octal System: An octal number system uses eight digits, 0 to 7.
  • Binary System: A binary number system uses only two digits, 0 and 1.

Below are the approaches to convert octal to binary in PHP:

Using PHP’s Built-in Functions

PHP provides built-in functions for octal and binary conversions. It is easy to convert Octal to Binary using PHP functions. The octdec() function converts an octal number to a decimal number, and the decbin() function converts a decimal number to a binary number.

Example: This example shows the conversion of Octal to binary using built-in functions.

PHP
<?php
    // Octal number
$octal = '46';

// Convert octal to decimal
$decimal = octdec($octal);

// Convert decimal to binary
$binary = decbin($decimal);

echo "Octal Number: $octal";
echo "\nEquivalent Binary Number: $binary";
?>

Output
Octal Number: 46
Equivalent Binary Number: 100110

Using Switch Case

Another approach to converting an octal number to a binary number involves switch case. This approach provides a clear illustration of the conversion process and can be customized to handle different input formats or error conditions as needed. Start by converting each digit in the octal number to its binary counterpart by using a switch statement. We can then find the binary representation of the entire octal number by concatenating the binary equivalents of each octal digit.

Example: This example shows the conversion of Octal to binary using custom functions.

PHP
<?php
function ConvertBinary($octal)
{
    $i = 0;

    $binary = (string)"";

    while ($i != strlen($octal))
    {
        switch ($octal[$i])
        {
        case '0':
            $binary.= "000";
            break;
        case '1':
            $binary .= "001";
            break;
        case '2':
            $binary .= "010";
            break;
        case '3':
            $binary .= "011";
            break;
        case '4':
            $binary .= "100";
            break;
        case '5':
            $binary .= "101";
            break;
        case '6':
            $binary .= "110";
            break;
        case '7':
            $binary .= "111";
            break;
        default:
            echo("\nInvalid Octal Digit ". 
                            $octnum[$i]);
            break;
        }
        $i++;
    }
    return $binary;
} 

// Driver code

$octal = "345";
$binary = convertBinary($octal);

echo "Octal Number: $octal";
echo "\nEquivalent Binary Number: $binary";

?>

Output
Octal Number: 345
Equivalent Binary Number: 011100101

Next Article

Similar Reads