Question

I have googled for it and most tutorials are cryptic. Can somebody teach me or even point me to a resource? I have a PHP background.

Was it helpful?

Solution

The context of what you're using it for matters.

Let's suppose you have a set of 8 boolean options. Let's call them opt1 through opt8. Now for some reason, we're storing all of these options in a single 8-bit value. This is not something you typically want to do, but it certainly has its uses, especially for interfacing with existing systems and APIs.

So, we have the following 8-bit (1-byte) number, represented in binary:

10010011

Each bit corresponds to a specific option, in this order:

87654321

With me so far? Now, let's get into some basic logic operators. Think boolean. If true OR true, then we get true. If true AND true, we get true. If true AND false we get false. We can do the same thing with bitwise operators.

Let's try 10010011 OR 11111111. Basically, we'll do that logic operator on each a bit, and get the result 11111111.

Why is this useful? Suppose if we want to get the value of just one place... maybe opt 7. We could do 10010011 AND 01000000. We will end up with a number representing only that one option. (Of course, if you want a numeric 1 or 0, you will need to divide by the appropriate place value.

There are many applications for this. How you use it depends on what you need.

The Wikipedia article on this isn't bad: http://en.wikipedia.org/wiki/Mask_(computing)

OTHER TIPS

this page actually seems to be a pretty good intro with plenty of examples

http://php.net/manual/en/language.operators.bitwise.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top