PHP base_convert() Function


Definition and Usage

The base_convert() function is versatile utility to convert a number with one base to another. The base is not restricted to binary, octal, hexadecimal or decimal. It can be any number between 2 and 36.

First argument to this function is a string that can contain alpha-numeric characters. Digits in a number with base>9 will be represented by alphabets a - z such that 10 is represented by 'a', 11 by 'b' upto 35 by 'z'

For example base_convert('1001', 2,10) converts '1001' from binary to decimal number which is 9

Syntax

base_convert ( string $number , int $frombase , int $tobase ) : string

Parameters

Sr.NoParameter & Description
1number
A string containing the number to be converted
2frombase
base of representation of number
3tobase
base to which number needs to be converted to

Return Values

PHP base_convert() function returns astring that represents the number so converted.

PHP Version

This function is available in PHP versions 4.x, PHP 5.x as well as PHP 7.x.

Example

 Live Demo

Following example converts '1001' from binary to decimal number system. −

<?php
   $arg='1001';
   $frombase = 2;
   $tobase = 10;
   $val=base_convert($arg,$frombase, $tobase);
   echo "base_convert(" . $arg . " from base " . $frombase . "to " . $tobase . ") = " . $val;
?>

Output

This will produce following result −

base_convert(1001 from base 2 to 10) = 9

Example

 Live Demo

Following example converts '12340' as in a number system 5 to one with 16 −

<?php
   $arg='12340';
   $frombase = 5;
   $tobase = 16;
   $val=base_convert($arg,$frombase, $tobase);
   echo "base_convert(" . $arg . " from base " . $frombase . "to " . $tobase . ") = " . $val;
?>

Output

This will produce following result −

base_convert(12340 from base 5 to 16) = 3ca

Example

 Live Demo

Characters other than alphabets (a-z) or digits (0-9) are ignored. In this example, '+' in the number string is ignored. −

<?php
   $arg='12+340';
   $frombase = 10;
   $tobase = 16;
   $val=base_convert($arg,$frombase, $tobase);
   echo "base_convert(" . $arg . " from base " . $frombase . "to " . $tobase . ") = " . $val;
?>

Output

This will produce following result −

base_convert(12+340 from base 10 to 16) = 3034

Example

 Live Demo

"CANDLE" is a number with 25 as its base. Following example converts it to Hexadecimal number system

<?php
   $arg='CANDLE';
   $frombase = 25;
   $tobase = 16;
   $val=base_convert($arg,$frombase, $tobase);
   echo "base_convert(" . $arg . " from base " . $frombase . " to " . $tobase . ") = " . $val;
?>

Output

This will produce following result −

base_convert(CANDLE from base 25 to 16) = 73d5c1d

Updated on: 29-Jun-2020

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements