When to use Bitwise Operators during webdevelopment?

Viewed 17503

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.

10 Answers

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.

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.

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.)

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.

This question is already answered but I would like to share my experience with &.

I have used & a short time ago to validate a signup form when I was doing an ASP.NET C# exercise where the short-circuited && would not achieve a desired effect as easily.

What I wanted to do was highlight all invalid fields in the form and show an error message label right beside each invalid field, and dehighlight all valid fields and remove the error messages from them.

The code I used it was something like this:

protected void btnSubmitClicked(...) {
  username = txtUsername.Text;
  email = txtEmail.Text;
  pass = txtPassword.Text;
  if (isUsernameValid(username) & isEmailValid(email) & isPasswordValid(pass)) {
    // form is valid
  } else {
    // form is invalid
  }
  ...
}

private bool isPasswordValid(string password) {
  bool valid = true;
  string msg = "";
  if (password.length < MIN_PASSWORD_SIZE) {
    valid = false;
    msg = "Password must be at least " + MIN_PASSWORD_SIZE + " long.";
  }

  highlightField(txtPassword, lblPassword, valid, msg);
  return valid;
}

private void highlightField(WebControl field, Label label, string valid, string msg) {
  if (isValid) {
    // de-highlight
    field.BorderColor = VALID_FIELD_COLOR;
  } else {
    // highlight the text field and focus on it
    field.BorderColor = INVALID_FIELD_COLOR;
    field.Focus();
  }

  label.Text = msg;
}

// and other similar functions for username and email

Were I to use && instead of &, the if-statement in btnSubmitClicked method would highlight only the very first invalid field, and all the other invalid fields after that would not be highlighted and its error message not shown because short-circuited && would stop checking the condition after a false is encountered.

There may be a better way to achieve the same thing, but I found & useful at that time.

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.

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.

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.

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;
}
Related