2.5 Converting Numbers Between Different Bases


2.5 Converting Numbers Between Different Bases

You want to convert a number from one base to another ”for example, from an octal or hexadecimal number to a decimal number.

Technique

Use the octdec() and hexdec() functions to convert between octals and hexadecimals to decimals:

 <?php $num = octdec ($octadecimal_num); $num = hexdec ($hexadecimal_num); ?> 

For other conversions use PHP's base_convert( ) function. For example, there is no binoct() function to convert a binary number to octal, so instead you can write your own:

 <?php function binoct($number) {     return base_convert($number, 2, 8); } ?> 

Comments

The octdec() and hexdec() functions will convert octal and hexadecimal numbers to decimal numbers. If you want to convert your numbers back to octal and hexadecimal, use the decoct() and dechex() functions.

Usually, these will take care of most of your needs, but sometimes it's necessary to convert between weird bases, so base_convert() comes to the rescue. base_convert() takes a string representing the number, the base you're converting from, and the base you're converting to. Both bases have to be between 2 and 36. The reason is that digits in the numbers of base higher than 10 are represented with letters a through z, where a means 10, b means 11, and z means 36. In some cases, base_convert() could even be used as a primitive encryption function.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net