Re: Help with some clever bit operations

From: Date: Tue, 13 Jun 2006 15:22:48 +0000
Subject: Re: Help with some clever bit operations
References: 1 2 3 4 5  Groups: php.general 
Request: Send a blank email to php-general+get-237903@lists.php.net to get a copy of this message
Robert Cummings wrote: > On Tue, 2006-06-13 at 11:03, Jochem Maas wrote: >> Robert Cummings wrote: >>> On Tue, 2006-06-13 at 06:22, Jochem Maas wrote: >>>> My brain needs a crutch when trying doing this kind of thing >>>> (normally I only write hex number literally when dealing with bitwise stuff - >>>> the conversion stuff still makes my head spin) - this is what this table is for: >>>> >>>> 128 64 32 16 8 4 2 1 >>>> 1 0 1 1 0 1 0 1 >>>> 0 1 0 1 1 1 0 0 >>>> 0 0 0 0 1 1 1 1 >>>> >>>> and then I did this - hopefully it shows what you can/have to do: >>>> >>>> <?php >>>> >>>> // set some values >>>> $oldval = 128 + 32 + 16 + 4 + 1; // 10110101 >>>> $update = 64 + 16 + 8 + 4; // 01011100 >>>> $mask = 8 + 4 + 2 + 1; // 00001111 >>> You could just do the following: >>> >>> $oldval = bindec( '10110101' ); >>> $update = bindec( '01011100' ); >>> $mask = bindec( '00001111' ); >> when I was writing the reply I played with about 5 different >> conversion funcs - pretty everything expect bindec() !!! >> >> I guess i was being lazy - but then I alway think directly in hex numbers >> when doing bitwise stuff (at least I use hex notation for the constant value >> that I almost invariably end up creating) >> >> anyway cheers for the lightbuld moment :-) > > Well yours is at least faster since there's no function calls. Though > one can also do the following to avoid memorizing decimal bit values :) > > $oldval = (1 << 7) + (1 << 5) + (1 << 4) + (1 << 2) + (1 << 0); > $update = (1 << 6) + (1 << 4) + (1 << 3) + (1 << 2); > $mask = (1 << 3) + (1 << 2) + (1 << 1) + (1 << 0); cool - more brainfood. thanks! > > :) > > Cheers, > Rob.

« previous php.general (#237903) next »