PHP - Number: Converting Between Bases



PHP Number Tips - Part 4: If you want to convert a number to a different base such as binary, octal, hexadecimal, or custom, so you can use PHP's decbin( ), decoct( ), dexhec( ), or base_convert( ) functions such as:
<?php
//define number
$num = 100;

//convert to binary
//result: "Binary: 1100100 "
$bin = decbin($num);
echo "Binary: $bin ";

//convert to octal
//result: "Octal: 144 "
$oct = decoct($num);
echo "Octal: $oct ";

//convert to hexadecimal
//result: "Hexadecimal: 64 "
$hex = dechex($num);
echo "Hexadecimal: $hex ";

//convert to base 6;
//result: "Base6: 244"
$base6 = base_convert($num, 10, 6);
echo "Base6: $base6";
?>

PHP comes with the number of functions to convert a number from one base to another. In the above, the listing takes a base-10 (decimal) number and converts it to binary, octal, and hexadecimal wiith the decbin( ), decoct( ), and dechex( ) functions respectively. To convert in the opposite direction, you only have to use the bindec( ), octdec( ), and hexdec( ) functions. If you need to convert a number to or from a custom base, you can use the base_convert( ) function which accepts three arguments: the number, the base it's currently in, and the base it's to be converted to.

Here is the example of using the dechex( ) function:

<?php
//function to convert RGB colors to their hex values
function rgb2hex($r, $g, $b) {
return sprintf("#%02s%02s%02s", dechex($r), dechex($g), ↵
dechex($b));
}

//result: "#00ff40"
$hex = rgb2hex(0,255,64);
echo $hex;
?>




Tag: number, convert Category: PHP Application, PHP Basic Post : March 16th 2008 Read: 430 Bookmark and Share

blog comments powered by Disqus