PHP base_convert() function


The base_convert() function in PHP is used to convert a number from one base to another. This function is particularly useful when dealing with numeral systems such as binary (base 2), octal (base 8), decimal (base 10), and hexadecimal (base 16).

Syntax:

base_convert($number, $from_base, $to_base)

Parameters:

  • $number: The number to be converted, provided as a string. This is the value that you want to convert from one base to another.
  • $from_base: The base of the input number (the base of the original number).
  • $to_base: The base to which you want to convert the number.

Return Value:

  • The function returns the converted number as a string. If the conversion fails or if the input number is invalid for the specified base, it may return FALSE.

Valid Base Ranges:

  • The base can be any integer from 2 to 36. This means you can use it for binary (base 2), octal (base 8), decimal (base 10), hexadecimal (base 16), and up to base 36, which includes alphanumeric characters (0-9 and a-z).

Example 1: Converting from Binary to Decimal

<?php $binary_number = "1010"; // Binary representation of 10 // Convert binary to decimal $decimal_number = base_convert($binary_number, 2, 10); echo $decimal_number; ?>

Output:

10

In this example, the binary number 1010 is converted to its decimal equivalent, 10.

Example 2: Converting from Decimal to Hexadecimal

<?php $decimal_number = "255"; // Decimal number // Convert decimal to hexadecimal $hexadecimal_number = base_convert($decimal_number, 10, 16); echo $hexadecimal_number; ?>

Output:

ff

Here, the decimal number 255 is converted to its hexadecimal representation, ff.

Example 3: Converting from Hexadecimal to Octal

<?php $hexadecimal_number = "1A"; // Hexadecimal representation // Convert hexadecimal to octal $octal_number = base_convert($hexadecimal_number, 16, 8); echo $octal_number; ?>

Output:

32

In this example, the hexadecimal number 1A is converted to its octal equivalent, 32.

Example 4: Invalid Conversion

<?php $invalid_number = "123G"; // Invalid character for base 10 // Attempt to convert invalid number $result = base_convert($invalid_number, 10, 16); var_dump($result); ?>

Output:

bool(false)

In this case, since the character G is not valid in base 10, the function returns FALSE.

Practical Usage:

  • The base_convert() function is useful in applications where you need to work with different numeral systems, such as converting between binary, octal, decimal, and hexadecimal representations.
  • It's often used in programming, networking, and cryptography, where different number bases are common.

Summary:

  • base_convert($number, $from_base, $to_base) converts a number from one base to another, supporting bases from 2 to 36.
  • It returns the converted number as a string and may return FALSE for invalid input.
  • This function is helpful in various fields such as programming, data representation, and network address calculations.