What's wrong with this

Hi Folks

Okay, I know it's late and my brain is asleep but I just can't work out why
this doesn't work. I'm trying to work out what bits are on in a variable.
When I set the variable to, for example, 9, bits 8 and 1 should be set.
Anyway, here's the code:-

<?php

$apm = '9';
echo "APM = ".$apm."<br>";

if ($apm & '1') echo "<br>1";
if ($apm & '2') echo "<br>2";
if ($apm & '4') echo "<br>4";
if ($apm & '8') echo "<br>8";
if ($apm & '16') echo "<br>16";
if ($apm & '32') echo "<br>32";
if ($apm & '64') echo "<br>64";
if ($apm & '128') echo "<br>128";
if ($apm & '256') echo "<br>256";
if ($apm & '512') echo "<br>512";


And here's the result I'm getting:-

APM = 9

1
8
16
32
128
512

I can understand the 1 and 8 but why are 16,32,128 and 512 coming up?
Should I go to bed and look at it in the morning when no doubt everything
will be obvious?
Mad Hatter [ So, 11 Februar 2007 00:37 ] [ ID #1625739 ]

Re: What's wrong with this

> I can understand the 1 and 8 but why are 16,32,128 and 512 coming up?
> Should I go to bed and look at it in the morning when no doubt everything
> will be obvious?

Because you are using the strings and the result are related to the ascii
values.
try this

<?php
$apm = 9;
echo "APM = " . (string)$apm ."<br>";

if ($apm & 1) echo "<br>1";
if ($apm & 2) echo "<br>2";
if ($apm & 4) echo "<br>4";
if ($apm & 8) echo "<br>8";
if ($apm & 16) echo "<br>16";
if ($apm & 32) echo "<br>32";
if ($apm & 64) echo "<br>64";
if ($apm & 128) echo "<br>-128<br>";
if ($apm & 256) echo "<br>256";
if ($apm & 512) echo "<br>512";
?>

In any case use the type cast to avoid problems
expecially for this kind of (and math) operations.

Regards.

L. A. Iarrusso
info [ So, 11 Februar 2007 00:58 ] [ ID #1625740 ]

Re: What's wrong with this

Hi

> Because you are using the strings and the result are related to the ascii
> values.
> try this

[snipped]
That works. Thanks.
>
> In any case use the type cast to avoid problems
> expecially for this kind of (and math) operations.

Sorry, you've lost me there. What's a type cast?
Mad Hatter [ So, 11 Februar 2007 01:06 ] [ ID #1625741 ]

Re: What's wrong with this

Mad Hatter schrieb:
> Sorry, you've lost me there. What's a type cast?

type cast is a kind of conversion of a data type, e.g.

[1] intval("3");

returns the value of the string "3" as an integer.

HTH a little

[1]http://www.phpnoise.com/tutorials/22/5
MC [ So, 11 Februar 2007 23:13 ] [ ID #1625745 ]

Re: What's wrong with this

Hi

> type cast is a kind of conversion of a data type, e.g.
>
> [1] intval("3");
>
> returns the value of the string "3" as an integer.
>
> HTH a little
>
> [1]http://www.phpnoise.com/tutorials/22/5

Helped a lot, thanks
Mad Hatter [ So, 11 Februar 2007 23:45 ] [ ID #1625746 ]
PHP » alt.php » What's wrong with this

Vorheriges Thema: Creating black images when trying to create thumbnails
Nächstes Thema: looking for volunteer to help with website