Name

base_convert()

Synopsis

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

It is impractical for PHP to include separate functions to convert every base to every other base, so they are grouped into one function: base_convert(). This takes three parameters: a number to convert, the base to convert from, and the base to convert to. For example, the following two lines are identical:

    print decbin(16);
    print base_convert("16", 10, 2);

The latter is just a more verbose way of saying "convert the number 16 from base 10 to base 2." The advantage of using base_convert() is that we can now convert binary directly to hexadecimal, or even crazier combinations, such as octal to duodecimal (base 12) or hexadecimal to vigesimal (base 20).

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.

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.