| by Arround The Web | No comments

How to Use base_convert Function in PHP

In PHP, the base_convert() function is a useful tool that helps you convert numbers between different number systems or bases. It allows you to convert numbers from one base to another, such as changing a decimal number to binary or hexadecimal.

In mathematics, numbers can be represented in various bases, like binary (base 2), decimal (base 10), octal (base 8), and hexadecimal (base 16) and each digit in a number represents a value multiplied by the corresponding power of the base.

Syntax for base_convert() in PHP

The base_convert() function in PHP follows a simple syntax:

base_convert($number, $from_base, $to_base)

 
The given syntax shows that the function accepts three parameters given as:

    • $number: This is a mandatory argument that specifies a number that we need to convert from its current base to another base.
    • $from_base: This mandatory argument specifies the base value that the number currently has.
    • $to_base: This mandatory argument specifies the base value in which the number needs to be converted.

Return Value: The base_convert() function returns a converted number as a string.

Example 1

The following code performs decimal number to binary conversion using the PHP base_convert() function.

<?php
$decimal_number = 10;
$binary_number = base_convert($decimal_number, 10, 2);
echo "The binary representation of $decimal_number is: $binary_number";
?>

 

Example 2

The following code performs binary number to decimal conversion using the PHP base_convert() function.

<?php
$binary_number = "10101";
$decimal_number = base_convert($binary_number, 2, 10);
echo "The decimal representation of $binary_number is: $decimal_number";
?>

 

Example 3

The following code performs hexadecimal number to octal conversion using the PHP base_convert() function.

<?php
$hex_number = "7F";
$octal_number = base_convert($hex_number, 16, 8);
echo "The octal representation of $hex_number is: $octal_number";
?>

 

Conclusion

The base_convert() function in PHP is an effective tool for converting numbers between different number systems or bases. By understanding number systems and bases, such as decimal, binary, octal, and hexadecimal, we can use base_convert() to easily convert numbers from one base to another. With the examples provided, you can see how simple it is to perform conversions using the base_convert() function in PHP.

Share Button

Source: linuxhint.com

Leave a Reply