|
Posted by shimmyshack on 12/02/07 03:42
On Dec 2, 2:54 am, ZeldorBlat <zeldorb...@gmail.com> wrote:
> On Dec 1, 9:30 pm, Rob Wilkerson <r.d.wilker...@gmail.com> wrote:
>
>
>
> > I'm attempting to do some work around existing code that uses bitwise
> > operations to manage flags passed into a function and I'm quite
> > frankly unequipped to do so. I've never done much with bitwise
> > operations and all the reading I've done today doesn't appear to be
> > helping me much. I'm hoping someone here can provide a remedial
> > lesson. Given the following constants:
>
> > define('FLAG_1, 1);
> > define('FLAG_2', 2);
> > define('FLAG_3', 4);
> > define('FLAG_4', 8);
> > define('FLAG_5', 16);
> > define('FLAG_6', 32);
> > define('FLAG_7', 64);
> > define('FLAG_8', 128);
> > define('FLAG_9', 256);
> > define('FLAG_10', 512);
> > define('FLAG_11', 1024);
> > define('FLAG_12', 2048);
>
> > I'm making this call:
>
> > $foo = my_function ( 'arg1', 'arg2', FLAG_1|FLAG_6|FLAG_4 );
>
> > To this function signature:
>
> > function my_function ( $arg1, $arg2='blah', $flags=NULL )
>
> > Inside the function, if I just echo the value of $args I get "41".
>
> > Is that correct? From my reading, it doesn't seem correct, but it may
> > just be my ignorance in this area. Any assistance reading and
> > understanding this stuff would be much appreciated.
>
> > Thanks.
>
> > Rob
>
> FLAG_1 = 1 = 000001
> FLAG_6 = 32 = 100000
> FLAG_4 = 8 = 001000
>
> If we OR them all together we get 101001 = 41. So that's correct.
>
> Inside your function if you want to check if any particular flag was
> set you would do it like this:
>
> if($flags & FLAG_6) {
> echo 'FLAG_6 was set';}
>
> else {
> echo 'FLAG_6 was not set';
>
> }
>
> So, in your example, $flags & FLAG_6 would be true because:
>
> $flags = 41 = 101001
> FLAG_6 = 32 = 100000
>
> If we AND them together we have 100000 which, inside an if statement,
> evaluates to true.
you can think of it like so
"if it is in a and b then put a 1"
so what does
a & b
give you
"if it is in a and b then put a 1"
convert a and b to binary bits if needed
then think of the bits in both,
and run your mental eye down the columns,
put a 1 where the bit is set for both a and b, and a 0 where it isn't
then convert the result into decimal if needed.
17 & 8
10001
01000
so the answer is
10001
01000
00000 (no 1 appears in the any once column)
0 in decimal
how about 7 & 8
0111
1000
again 0
8 & 9
01000
01001
01000
8
with | it's similar
"if it is in a OR b" then put a 1
17 | 8
10001
01000
11001
25
notice this could almost be seen as adding up but it isn't, here's 8
and 9 again:
8 | 9
01000
01001
01001
9
where the two 1 occur twice in the same column we don't end up
doubling it, we just put a 1 in the column if there is a 1 in the
other column in EITHER row.
Navigation:
[Reply to this message]
|