Binary to Octal Converter in PHP

Converting a binary number to an octal number is a common task in programming. In this article, we will explore how to create a Binary to Octal Converter in PHP.

Note:

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

These are the following approaches:

Table of Content

  • Using PHP’s Built-in Functions
  • Using Manual Conversion

Using PHP’s Built-in Functions

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

Example: This example shows the conversion of Binary to octal using built-in functions.

PHP
<?php

// Binary number
$binary = '101010';

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

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

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

?>

Output
Binary Number: 101010
Equivalent Octal Number: 52

Using Manual Conversion

Another approach to converting a binary number to an octal number involves manual conversion. This method is beneficial for deeper understanding of the conversion process. Start by padding the binary number with zeros to ensure its length is a multiple of 3. This is necessary because each octal digit corresponds to three binary digits. Next, split the padded binary number into groups of 3 digits. For each group of 3 binary digits, convert it to its decimal equivalent using the bindec() function. Then, convert the decimal number to its octal representation using the decoct() function.

Example: This example shows the conversion of Binary to octal using custom functions.

PHP
<?php

function convertOctal($binary) {

    // Add zeros to left to make its
    // length to multiple of 3
    $length = strlen($binary);
    $padding = $length % 3 == 0 ? 0 : 3 - ($length % 3);
    $binary = str_repeat('0', $padding) . $binary;
    
    // Split the binary number into
    // groups of 3 digits
    $groups = str_split($binary, 3);
    
    // Convert each group to its
    // octal equivalent
    $octal = '';

    foreach ($groups as $group) {
        $decimal = bindec($group);
        $octal .= decoct($decimal);
    }
    
    return $octal;
}

// Driver Code
// Binary number
$binary = '101010';
$octal = convertOctal($binary);

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

?>

Output
Binary Number: 101010
Equivalent Octal Number: 52