views:

1766

answers:

9

Although I grasp the concept of Bitwise Operators, I can't say that I have come across many use cases during the webdevelopment process at which I had to resort to using Bitwise Operators.

  • Do you use Bitwise Operators?
  • Why do you use them?
  • What are some example use cases?

Please remember that this question is specifically intended for use of Bitwise Operators in web languages.

+13  A: 

My main use for bitwise operators could be relevant anywhere - representing a set of flags. For instance, you might have an integer in the database representing a set of security permissions for a user, and in your web app you would have to check those before continuing.

Those tend to only require & and | - e.g.

if ((permissions & Permission.CreateUser) != 0)
{
    ...
}

or

Permission requiredPermission = Permission.CreateUser
                                | Permission.ChangePassword;

Bit shifting operators are less useful in "business" applications in my experience.

Jon Skeet
Downvoters: Please explain your downvotes, or they're pointless.
Jon Skeet
+1  A: 

I use em every so often but never in places where I can avoid them. The most often I have used them are the following two situations.

  1. Encrypting form data from client using JavaScript when not over a secure connection, its not much but better than sending plain text.
  2. Streaming file structures (generally some binary file type) from PHP that are generated on the fly.
bmeck
Some examples would be nice.
Alix Axel
+1  A: 

Generally, you don't need to concern about operations at the bit level. You can think in bytes, ints, doubles, and other higher level data types. But there are times when you'd like to be able to go to the level of an individual bit.

One of the most common utilization cases of the bitwise operators are the flags (php example). The bitwise operators are also used in binary file IO operations.

CMS
+1  A: 

On the off-topic side of things, in high-level languages, especially in parsed languages (such as PHP), bitwise operations are tons slower[citation needed] than the normal arithmetic. So, while Jon's permission checking might be ok from a performance standpoint, it's not very 'native' in the web domain.

Henrik Paul
A: 

Besides from flags, there is not much reason to use bit-operations in scripting languages. But once you delve into the lower levels of your stack, bit-operations become more and more critical.

Robert Gould
+14  A: 

I'm going to be more explicit here because I think bitwise masks are a great tool that should be in any devs belt. I'm going to try to expand on the answers above. First, an example of using an integer to maintain state flags (common usage):

// These are my masks
private static final int MASK_DID_HOMEWORK  = 0x0001;
private static final int MASK_ATE_DINNER    = 0x0002;
private static final int MASK_SLEPT_WELL    = 0x0004; 

// This is my current state
private int m_nCurState;

To set my state, I use the bitwise OR operator:

// Set state for'ate dinner' and 'slept well' to 'on'
m_nCurState = m_nCurState | (MASK_ATE_DINNER | MASK_SLEPT_WELL);

Notice how I 'or' my current state in with the states that I want to turn 'on'. Who knows what my current state is and I don't want to blow it away.

To unset my state, I use the bitwise AND operator with the complement operator:

// Turn off the 'ate dinner' flag
m_nCurState = (m_nCurState & ~MASK_ATE_DINNER);

To check my current state, I use the AND operator:

// Check if I did my homework
if (0 != (m_nCurState & MASK_DID_HOMEWORK)) {
    // yep
} else { 
    // nope...
}

Why do I think this is interesting? Say I'm designing an interface that sets my state. I could write a method that accepts three booleans:

void setState( boolean bDidHomework, boolean bAteDinner, boolean bSleptWell);

Or, I could use a single number to represent all three states and pass a single value:

void setState( int nStateBits);

If you choose the second pattern you'll be very happy when decide to add another state - you won't have to break existing impls of your interface.

My two cents. Thanks.

tyler
A very helpful answer! deserves to be on top, for sure.
Ace
Personally, I hate this "pattern" with a vengeance. It's very close to code obfuscation.
Michael Borgwardt
Though you are welcome to your opinion, I maintain that using bit fields to store state can be clean, concise and in some cases optimal. If it's the syntax that makes you uncomfortable then package the operations in problem specific convenience methods and avoid exposing the underlying implementation to your caller. As for code obfuscation, does a "pattern" exist that can't be obfuscated by an inexperienced developer?
tyler
A: 

For Java programmers the xor bitwise operator (^) provides a useful way to code an exclusive OR test between two booleans. Example:

boolean isFoo = ...
boolean isBar = ...

if (isFoo ^ isBar) {
    // Either isFoo is true or isBar is true, but not both.

Note: there's no actual bit manipulation going on here but it is a useful way to use the xor bitwise operator (in the web tier or anywhere else).

(Same may apply to C#, since it's so similar to Java. Not sure, though.)

A: 

The only time I have had to use them outside of authorizing access was for a project I was doing for a parser that took Color IDs assigned to ints

i.e

$color_red= 1;
$color_blue = 2;
$color_yellow = 8;

$color_purple = 3;
$color_orange = 9;
$color_green  = 10;

then I was given a property

$can_collect_200_dollars = 10;

then used bitwise to compare the color given with the property

if($given_color & $can_collect_200_dollars)
{
    $yay_i_got_200_dollars = true;
}else{
    $bummer_i_am_going_to_jail = true;
}
Jayrox
A: 

I think bitwise operators are very strong if used intelligently.

Suppose you have a "Online Store". And some of your items fall in more that one Categories.

Either you have to Create a Many-to-Many relation. Or you can give your Categories an extra Binary-ID and in your product just store the Bitwise combinition of Categories-IDs

I think in few line I can't explain in detail. SORRY

This can also be very weak if you have tons of categories.
Alix Axel