On Tuesday 13 June 2006 12:22, Jochem Maas wrote:

> 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.
> 
> 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
> 
> // do a 'bit' of surgery ...
> $add    = $mask & $update;
> $keep   = ~$mask & $oldval;
> $newval = $keep | $add;
> 
> // show what happened
> var_dump(
> str_pad(base_convert($oldval, 10, 2), 8, "0"),
> str_pad(base_convert($update, 10, 2), 8, "0"),
> str_pad(base_convert($mask, 10, 2), 8, "0"),
> str_pad(base_convert($add, 10, 2), 8, "0"),
> str_pad(base_convert($keep, 10, 2), 8, "0"),
> str_pad(base_convert($newval, 10, 2), 8, "0")
> );
> 
> ?>
> 
>> 
>> How do I combine A, B and C to get that result?
>> 
>> 
>> Thanks,
>> Niels
>>


Thanks, I appreciate your effort! Working code with inlined pun -- very
nice!

Regards,
Niels

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to