42

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.

Aron Rotteveel
  • 81,193
  • 17
  • 104
  • 128
  • There is nothing specific about using bitwise operators in "web languages". It's as pointless as asking *when would you use a radial blur filter in web design?*. Duplicate of http://stackoverflow.com/questions/276706/what-are-bitwise-operators, http://stackoverflow.com/questions/1746613/bitwise-operation-and-usage , http://stackoverflow.com/questions/1167956/resources-to-learn-bitwise-programming and others. – Ricardo Tomasi Jan 21 '14 at 02:53
  • This question is not pointless, when you consider the volume of programming learning materials focused on web dev that insist on teaching bitwise operands / operators. Its fun code golf, and useful to comprehend the application of Computer Science as a whole, but doubtful you will have any practical use for it in webdev - so why the proliferation of teaching it? – Todd Mar 13 '18 at 22:25

10 Answers10

86

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
  • 2,865
  • 1
  • 23
  • 28
  • 3
    A very helpful answer! deserves to be on top, for sure. – Ace Nov 04 '08 at 13:45
  • 26
    Personally, I hate this "pattern" with a vengeance. It's very close to code obfuscation. – Michael Borgwardt Apr 21 '09 at 08:35
  • 7
    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 Apr 29 '09 at 15:38
  • 4
    Best bitmap tutorial ever. Short and to the point. I just learned how bitmaps work without trying. – niken Feb 12 '14 at 22:10
  • So if one would declared int constant variables as states\flags the later would be a perfectly clean solution vs having to maintain multiple bool parameters. Great thanks. – dynamiclynk Apr 09 '14 at 20:04
  • @tyler you didn't mention one important point is that your masks must have 1 bit "ON" only. Example: 001 or 010 or 100 etc... – redochka Jan 13 '16 at 23:24
  • @redsonic I'm not sure that I agree with you. I think I see where you're coming from, but consider the case of an "all" mask like 0xFFFF where all bits are "on" - this is a totally valid mask. – tyler Jan 14 '16 at 17:50
  • @tyler What would be similar operation for bitwise XOR (^) – Bagira Jan 08 '21 at 11:56
54

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 18
    Downvoters: Please explain your downvotes, or they're pointless. – Jon Skeet Apr 21 '09 at 08:43
  • 2
    +1, but shifting operations are not that useless when it comes to cryptography. For instance, MD5 algorythm uses bit shifting. It may be a bad example because MD5 is already implemented in PHP, but that is first thing that came to my mind. – Hnatt Aug 16 '11 at 10:22
  • 8
    @Hnatt: Exactly - it's hardly *business* logic, unless your business is providing crypto functions. – Jon Skeet Aug 16 '11 at 10:23
  • 2
    Yes, crypto functions business is still business. Oh, and one more thing. If your business is working with RGB or HSL colours then bit shifting can help you too. – Hnatt Aug 16 '11 at 12:05
  • 1
    @Hnatt: Sure - but those are very specialist businesses, whereas *most* business developers don't need that functionality, compared with more common operators which pretty much *all* developers need. – Jon Skeet Aug 16 '11 at 12:19
  • Can you please explain what will be the result of `Permission.CreateUser | Permission.ChangePassword;` ? @JonSkeet – MaheshVarma Jan 09 '14 at 05:15
  • 1
    @MaheshVarma: It's an enum value representing the combination of those flags. See http://stackoverflow.com/questions/8447 – Jon Skeet Jan 09 '14 at 12:49
14

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

  • 5
    Or you could write `if ((isFoo || isBar) && isFoo != isBar)` which may be more verbose, but will make sense to anyone without them having to google what `^` is. – CorayThan Aug 24 '14 at 17:55
  • 2
    Does this really answer when to use bitwise operators? – Tejas Manohar Oct 10 '14 at 13:17
  • 3
    Just `isFoo != isBar` would be equivalent and clearer. – Falk Hüffner Dec 29 '15 at 09:05
  • @CorayThan. If the user wanted to know what the "^" operator does, then they will find out. And as a bonus, that's one more person that is now aware of bitwise operations, and can implement that knowledge into their future work if they so wish. – thephpdev Oct 03 '16 at 13:03
  • Scrap this - I'm hungover. Original comment: @FalkHüffner, I'm not sure I follow your logic. What if `isFoo` and `isBar` were both `false`? The result will be `true`, and that is not correct for an XOR comparison. – thephpdev Oct 03 '16 at 13:06
  • @FalkHüffner. This is correct and we will not use this condition where one of them is true but not both. – Arefe Dec 21 '20 at 13:48
  • @thephpdev if both false it will NOT equal true. false != false equals false! For booleans, `^` is literally the same as `!=` – Hannes Schneidermayer Apr 30 '22 at 11:10
  • @HannesSchneidermayer – I don't remember typing this 6 years ago, though I have brushed up on my bitwise operators since – you could say I'm bit/wise/ (:-P) – thephpdev May 03 '22 at 08:12
7

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.

RestInPeace
  • 785
  • 1
  • 7
  • 19
6

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
  • 68,773
  • 61
  • 187
  • 272
2

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.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
1

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
  • 426
  • 2
  • 4
1

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
  • 66,919
  • 31
  • 85
  • 96
0

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
  • 4,335
  • 4
  • 40
  • 43
-2

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

user160820
  • 14,866
  • 22
  • 67
  • 94