Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
base_convert() function in PHP
The base_convert() function converts a number from one base to another, for example, octal number to decimal number. The base mentioned here should be between 2 and 36. Digits in numbers with a base greater than 10 are represented with the letters a-z, where a is 10, b is 11, c is 12, d is 13, and so on up to z which is 35.
Syntax
base_convert(num, original_base, to_base)
Parameters
num − The number to convert (as a string)
original_base − The original base of the number (between 2 and 36)
to_base − The base to convert to (between 2 and 36)
Return Value
The base_convert() function returns a string representing the number converted to the desired base.
Example 1: Octal to Decimal
Converting an octal number to decimal ?
<?php
$res = "0040";
echo base_convert($res, 8, 10);
?>
32
Example 2: Hexadecimal to Octal
Converting a hexadecimal number to octal ?
<?php
$res = "D365";
echo base_convert($res, 16, 8);
?>
151545
Example 3: Binary to Hexadecimal
Converting a binary number to hexadecimal ?
<?php
$res = "101101";
echo base_convert($res, 2, 16);
?>
2d
Example 4: Using Higher Bases
Converting between bases higher than 10 using alphabetic characters ?
<?php
// Convert base 36 to decimal
echo base_convert("zz", 36, 10) . "<br>";
// Convert decimal to base 36
echo base_convert("1295", 10, 36);
?>
1295 zz
Conclusion
The base_convert() function is useful for converting numbers between different number systems. It accepts bases from 2 to 36 and returns the converted value as a string, making it ideal for various mathematical and programming applications.
