..oO(Jack)
>On Mon, 04 Feb 2008 23:51:28 +0100, Michael Fesser <ne*****@gmx.de>
wrote:
>>The rest is easy:
* set a bit (OR): $value = $value | YOUR_BIT_CONSTANT
* unset a bit (AND NOT): $value = $value & ~YOUR_BIT_CONSTANT
* get a bit (AND): $isSet = $value & YOUR_BIT_CONSTANT
I haven't tried this yet but it looks like it should do the trick.
Binary logic isn't that complicated. You just have to remember how an
integer is represented in binary form and how the basic logic operations
AND, OR and NOT work with single bits. Often it helps to look at a so
called truth table:
http://en.wikipedia.org/wiki/Truth_table
These tables show what the result of such a logical operation will be,
dependent on the operands. The most important ones are the first three,
representing the three operations mentioned above.
>As I commented to Alexey, I don't understand how all this works yet.
And, to add to my confusion, it seems your way is quite different than
his. I have some learning to do. :)
The difference is that he uses bit shifting as explained in the reply
from ZeldorBlat, while my code directly accesses the bits by their
values.
Every bit position represents a power of 2, starting with 2^0 = 1 for
the first bit. The 6th bit for example is 2^(6-1) = 2^5 = 32. In general
the nth bit has the value 2^(n-1). If you know these simple values, you
can directly access all the bits without any shifting.
This has the advantage that it's possible to set/test multiple bits at
the same time with a single operation. But of course in other cases bit
shifting might be more appropriate or more efficient. For example a
single shift to the right is a very efficient way for a division by 2.
I hope you are not even more confused now than before. ;)
But once you've understood the basic principles, binary logic and bit
manipulations can be a really powerful tool.
Micha