RE: [PHP] Help with some clever bit operations
| From: | Niels | Date: | Tue, 13 Jun 2006 11:11:01 +0000 |
| Subject: | RE: [PHP] Help with some clever bit operations | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-237877@lists.php.net to get a copy of this message | ||
On Tuesday 13 June 2006 12:32, Ford, Mike wrote:
> On 13 June 2006 10:31, Niels wrote:
>
>> Hi,
>>
>> I have a problem I can solve with some loops and if-thens,
>> but I'm sure it
>> can be done with bit operations -- that would be prettier.
>> I've tried to
>> work it out on paper, but I keep missing the final solution. Maybe
>> I'm missing something obvious...
>>
>> The problem: A function tries to update an existing value, but is only
>> allowed to write certain bits.
>>
>> There are 3 variables:
>> A: the existing value, eg. 10110101
>> B: what the function wants to write, eg. 01011100
>> C: which bits the function is allowed to write, eg. 00001111
>>
>> With these examples, 10111100 should be written.
>>
>> How do I combine A, B and C to get that result?
>
> First use & (bitwise-and) to mask out bits the function is not allowed to
> write:
>
> $b & $c // result is 00001100 given above inputs
>
> Then mask the bits that the function will write out of the original value
> - negate the mask and use & again:
>
> $a & ~$c // result is 10110000
>
> Then combine the two using | (bitwise-or):
>
> ($a & ~$c) | ($b & $c) // result is 10111101
[snip]
Thanks! I appreciate your effort!
Regards,
Niels