PHP Numbers Converting Between Bases - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Numbers Converting Between Bases - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Friday, May 10, 2019

PHP Numbers Converting Between Bases

PHP Numbers



Converting Between Bases


Problem

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

Solution

Use the base_convert() function:

            // hexadecimal number (base 16)
            $hex = 'a1';

            // convert from base 16 to base 10
            // $decimal is '161'
            $decimal = base_convert($hex, 16, 10);

Discussion

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():

            // 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:
           
            $red = 0;
            $green = 102;
            $blue = 204;
            // $color is '#0066CC'
            $color = sprintf('#%02X%02X%02X', $red, $green, $blue);


No comments:

Post a Comment

Post Top Ad