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:
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
Output:
In this example, the binary number 1010
is converted to its decimal equivalent, 10
.
Example 2: Converting from Decimal to Hexadecimal
Output:
Here, the decimal number 255
is converted to its hexadecimal representation, ff
.
Example 3: Converting from Hexadecimal to Octal
Output:
In this example, the hexadecimal number 1A
is converted to its octal equivalent, 32
.
Example 4: Invalid Conversion
Output:
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.