2.7 Finding the Binary Representation of a Number


You want to find the binary representation of a given number or the number that represents a binary string.

Technique

Use the decbin() and bindec() functions to convert back and forth:

 <?php $num = 23; $binary  = decbin ($num); $decimal = bindec ($binary); print "The number $decimal is equivalent to the binary $binary"; ?> 

Comments

The decbin() function converts a decimal number to its binary equivalent; in contrast, the bindec() function converts a binary number to its decimal equivalent. Another method is to use PHP's base_convert() function:

 <?php $num = 23; $binary  = base_convert ($num, 10, 2); $decimal = base_convert ($binary, 2, 10); print "The number $decimal is equivalent to the binary $binary"; ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net