note 104311 modified in function.decbin by danbrown

From: Date: Wed, 08 Jun 2011 14:38:05 +0000
Subject: note 104311 modified in function.decbin by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-180337@lists.php.net to get a copy of this message
Here's a generic binary output formatter. It is based on the function in above comments, but lets you specify how many bits your want formatted. <?php /** * Output an x bit string representing a binary value. * Default is 8 bits ie. 0000 0000 * eg. fmt_binary($x,32) : output a 32-bit binary representation of $x * @param string $x x-bit formatted binary */ function fmt_binary($x, $numbits = 8) { // Convert to binary $bin = decbin($x); $bin = substr(str_repeat(0,$numbits),0,$numbits - strlen($bin)) . $bin; // Split into x 4-bits long $rtnval = ''; for ($x = 0; $x < $numbits/4; $x++) { $rtnval .= ' ' . substr($bin,$x*4,4); } // Get rid of first space. return ltrim($rtnval); } ?> --was-- Here's a generic binary output formatter. It is based on the function in above comments, but lets you specify how many bits your want formatted. /** * Output an x bit string representing a binary value. * Default is 8 bits ie. 0000 0000 * eg. fmt_binary($x,32) : output a 32-bit binary representation of $x * @param string $x x-bit formatted binary */ function fmt_binary($x, $numbits = 8) { // Convert to binary $bin = decbin($x); $bin = substr(str_repeat(0,$numbits),0,$numbits - strlen($bin)) . $bin; // Split into x 4-bits long $rtnval = ''; for ($x = 0; $x < $numbits/4; $x++) { $rtnval .= ' ' . substr($bin,$x*4,4); } // Get rid of first space. return ltrim($rtnval); } http://php.net/manual/en/function.decbin.php

« previous php.notes (#180337) next »