Re: Help with some clever bit operations

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



David Tulloh wrote:
> The example starting values
> $existing = 181; # = 10110101
> $new = 92; # = 01011100
> $mask = 15; # = 00001111
> 
> Get the bits that will be changed
> $changing = $new & $mask; # = 12 = 00001100
> 
> Get the bits that won't be changed
> $staying = $existing & ~$mask; # = 176 = 10110000
> 
> Combine them together
> $result = $changing ^ $staying; # = 188 = 10111100

heck, Davids 'result' line is more correct than mine I believe -
he uses an XOR operation where I used an OR operation - both have the same
result because the set of bits that are 'on' in the first operand are mutually
exclusive to the set of bits that are 'on' in the second operand.

> 
> 
> David
> 
> 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?
>>
>>
>> Thanks,
>> Niels
>>
> 

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


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux