note 77616 deleted from function.decbin by danielc

From: Date: Mon, 27 Apr 2009 02:23:00 +0000
Subject: note 77616 deleted from function.decbin by danielc
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153798@lists.php.net to get a copy of this message
Note Submitter: Sam Yong - hellclanner [at] live dot com Reason: 2 ---- I was trying out and learning about bits when i made one of the function worked as expected. The function i just made is a clone of decbin(); but it is not as good as the native one. Just a simple idea of how decbin works. For numbers, you need to specify the (int) type before using because the result might be different if you leave it out. Great value of float specified will result in an overflow so the max number is returned(0xFFFFFFFF). The Return is a string with binary in it. I have managed to fix the 32th resource bit loss by reading up on other codes written by others' notes on php.net <?php function mydecbin($a = 0){ if(is_int($a)){$a = (float)$a;} $a = (float)((float)$a>=0?(float)$a:(float)$a*-1); if($a >= 0xFFFFFFFF){return (string)"11111111111111111111111111111111";} $buff =array(); $res = ($a & 0x7FFFFFFF) >> 32; if(0x80000000 & $a){ $res |= (1<<(31-32)); } $a = floor($a / 2); while(ceil($a / 2) > 0){ if(ceil($a%2) > -1){$buff[] = ceil($a%2);} $a = floor($a / 2);} $buff = array_reverse($buff); $r = ''; foreach($buff as $b){$r .= $b;} $r .= floor(($res>0?$res:$res*-1)%2); return (string)$r; } // Usage: $n = (int)281474976711000; echo "\n\n"; var_dump(mydecbin($n)); // var dump the returned value echo ' vs '."\n"; var_dump(decbin($n)); // do a check echo "\n"; var_dump(mydecbin($n) === decbin($n)); // value and type check /* Outputs: string(9) "101011000" vs string(9) "101011000" bool(true) */ ?> Cheers Sam Yong

« previous php.notes (#153798) next »