Categories
PHP Tips & Tutorials

PHP: Convert between Numerical Bases | Binary Number, Decimal Number, Octal Number and Hexadecimal Number Conversions

Different number notations for different numerical bases:

0144  // base 8
 100  // base 10
0x64  // base 16

To convert between number bases, use PHP base_convert() function:

$hex = 'a1'; // hexadecimal number (base 16)
$decimal = base_convert($hex, 16, 10); // $hex converted from base 16 to base 10 and $decimal is now 161
$bin = '101'; // binary number (base 2)
$decimal = base_convert($bin, 2, 10); // $bin converted from base 2 to base 10 and $decimal is now 5

base_convert() function changes a number string from the original base to the target base number string. Other than this, there are also other specialized base conversion functions in PHP that’s basically created around decimal (base 10):

// convert to base 10
print bindec(11011); // 27
print octdec(33);    // 27
print hexdec('1b');  // 27

// convert from base 10
print decbin(27);    // 11011
print decoct(27);    // 33
print dechex(27);    // 1b

By Yang Yang

Hello, I'm Yang. I build online businesses that please people. Want to join in and post some useful articles on Kavoir.com? Shoot me a message.