You need to convert a number from one base to another.

Use the **base_convert()** function:

1 2 3 4 5 6 |
// hexadecimal number (base 16) $hex = 'a1'; // convert from base 16 to base 10 // $decimal is '161' $decimal = base_convert($hex, 16, 10); |

The **base_convert()** function changes a string representing a number in one base to the correct string in another base.

It works for all bases from 2 to 36 inclusive, using the letters a through z as additional symbols for bases above 10. The first argument is the number to be converted, followed by the base it is in and the base you want it to become.

There are also a few specialized functions for conversions to and from base 10 and the most commonly used other bases of 2, 8, and 16. They’re **bindec()** and **decbin()**, **octdec()** and **decoct()**, and **hexdec()** and **dechex()**:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// convert from base 2 to base 10 // $a = 27 $a = bindec(11011); // convert from base 8 to base 10 // $b = 27 $b = octdec(33); // convert from base 16 to base 10 // $c = 27 $c = hexdec('1b'); // convert from base 10 to base 2 // $d = '11011' $d = decbin(27); // $e = '33' $e = decoct(27); // $f = '1b' $f = dechex(27); |

Note that the specialized functions that convert to base 10 return integers. The functions that convert from base 10 return strings.

Another alternative is to use the **printf()** family of functions, which allows you to convert decimal numbers to binary, octal, and hexadecimal numbers with a wide range of formatting, such as leading zeros and a choice between upper- and lowercase letters for hexadecimal numbers.

For instance, say you want to print out **HTML** color values. You can use the %02X format specifier:

1 2 3 4 5 |
$red = 0; $green = 102; $blue = 204; // $color is '#0066CC' $color = sprintf('#%02X%02X%02X', $red, $green, $blue); |