base conversion functions

The default base in PHP for reading in or printing out numbers is 10. In addition, you can instruct PHP to read octal numbers in base 8 (by starting the number with a leading 0) or hexadecimal numbers in base 16 (by starting the number with a 0x).

Once numbers are read in, of course, they are represented in binary format in memory, and all the basic arithmetic and mathematical calculations are carried out internally in base 2. PHP also has a number of functions for translating between different bases:

Base Conversion Functions
Function Behavior
BinDec() Takes a single string argument representing a binary (base 2) integer, and returns a string representation of that number in base 10.
DecBin() Like BinDec(), but converts from base 10 to base 2.
OctDec() Like BinDec(), but converts from base 8 to base 10
DecOct() Like BinDec(), but converts from base 10 to base 8.
HexDec() Like BinDec(), but converts from base 16 to base 10.
DecHex() Like BinDec(), but converts from base 10 to base 16.
baseconvert() Takes a string argument (the integer to be converted) and two integer arguments (the original base, and the desired base). Returns a string representing the converted number — digits higher than 9 (from 10 to 35) are represented by the letters a–z. Both the original and desired bases must be in the range 2–36.

Note

The base conversion functions expect their string arguments to be integers,
not floating-point numbers. That means you can’t use these functions to convert
a binary 10.1 to a decimal 2.5.

Caution

Use strings as arguments all the time for these functions. Doing otherwise is asking for trouble. Also, do not use the read formats for octal and hex to specify a numeric argument for these functions. Though it may work in some cases, it is slow and troublesome.

Advertisements

About samehramzylabib

See About on https://samehramzylabib.wordpress.com
This entry was posted in Coding, PHP Math and tagged , . Bookmark the permalink.

Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s