PHP base_convert() Function

In this chapter you will learn:

  1. Definition for PHP base_convert() Function
  2. Syntax for PHP base_convert() Function
  3. Parameter for PHP base_convert() Function
  4. Return for PHP base_convert() Function
  5. Example - Convert number with base
  6. Example - Convert a hexadecimal number to octal number
  7. Example - Convert an octal number to a decimal number
  8. Example - Convert an octal number to a hexadecimal number

Definition

We can use base_convert() to convert binary directly to hexadecimal, or octal to duodecimal (base 12) or hexadecimal to vigesimal (base 20).

Syntax

PHP base_convert() function's format is as follows.

string base_convert ( string num, int from_base , int to_base )

Parameter

base_convert() takes three parameters:

  • a number to convert,
  • the base to convert from, and
  • the base to convert to.

Return

The return value is the number converted to the specified base. The return type is String.

Example 1

For example, the following two lines are identical:


<?PHP
    print decbin(16); 
    print base_convert("16", 10, 2); 
?>

base_convert("16", 10, 2) is saying "convert the number 16 from base 10 to base 2.

The highest base that base_convert() supports is base 36, which uses 0?9 and then A?Z. If you try to use a base larger than 36, you will get an error.

The code above generates the following result.

Example 2

Convert a hexadecimal number to octal number:


<?php
$hex = "E196"; 
echo base_convert($hex,16,8); 
?>

The code above generates the following result.

Example 3

Convert an octal number to a decimal number:


<?php
$oct = "0031";
echo base_convert($oct,8,10);
?>

The code above generates the following result.

Example 4

Convert an octal number to a hexadecimal number:


<?php
$oct = "364";
echo base_convert($oct,8,16);
?>

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Definition for PHP bindec() Function
  2. Syntax for PHP bindec() Function
  3. Parameter for PHP bindec() Function
  4. Return for PHP bindec() Function
  5. Example - Convert binary to decimal