When to use Bitwise Operators during webdevelopment?

后端 未结 10 1297
Happy的楠姐
Happy的楠姐 2020-12-12 12:01

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 Bi

相关标签:
10条回答
  • 2020-12-12 12:24

    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;
    }
    
    0 讨论(0)
  • 2020-12-12 12:25

    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.

    0 讨论(0)
  • 2020-12-12 12:27

    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.

    0 讨论(0)
  • 2020-12-12 12:32

    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.

    0 讨论(0)
提交回复
热议问题