phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


PHP - Number: Converting Between Bases

Tag: number, convert   Category: PHP Application, PHP Basic
post: 16 Mar 2008 read: 40


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;
?>



| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


615
posting