Powers Gone Wrong?
[email protected] ("Jonathan Wright \(DjNA\)") Fri, 2 Jun 2000 21:13:31 +0100
| Newsgroups | php.general,php.version4 |
|---|---|
| Message-ID | <[email protected]> |
Hiya,
I'm a bit of a newbie to PHP (although I know quite a bit of Perl), and I
wrote some code to test out Powers (<<). It all seams to be working fine,
until it gets to 2^0 (two to the power zero). It should be 1 and it's giving
me 0.
Written into the code is a tester, for converting a number to binary. It's a
prototype for a selection I'm writing. Depending on what someone what's they
add up all of the numbers of the options, and this will decode them. If you
call powers.php?power=5, bit 2 and bit 0 should show positive, so selection
1 and 4 will run. If you call 6, bit 2 and 1 should show positive, but bit 0
does as well, as it's coming out 0.
This is my fault, or a possible bug? I think I've got it right. All the
other powers (bit 8 = 256, bit 16 = 65,536) seam correct, but why 0?
Thanks.
---powers.php----------------------------------
<html>
<head>
<title>PHP Testing - Powers</title>
</head>
<body>
<pre>
<?php
$binary="";
for ($i=16; $i>=0; $i--)
{ echo "2<<".$i." = ".(2 << ($i-1))."\n bit ".$i;
if (($power-(2 << ($i-1))) >= 0)
{ $power -= (2 << ($i-1));
$binary .= "1";
echo " -> <font color=#ff0000>Positive</font>\n"; }
else
{ echo " -> Negative\n";
$binary .= "0"; }
}
echo "Binary : ".$binary."\n\n\n";
?>
</pre>
</body>
<html>
-----------------------------------------------
Give it a go. I can't see the problem, unless it's my understanding ;-)
Thanks again.
- - - - - - - - - - - - - - - - - - - -
Jonathan Wright [DjNA]
[email protected]
www.djna.fsnet.co.uk
ICQ [21961373]