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

Related Posts:

Google

Leave a reply

Google

Good Boys

Do NOT subscribe, I’m a shameless self-promoter!

Thesis Theme for WordPress:  Options Galore and a Helpful Support Community

We are …

We write with …

Written with Windows Live Writer

We appreciate your …