Bitwise AND operator use

Viewed 93

I'm trying to analyze some old code to understand what is it doing in case of error. This is the function:

error = -11; 
protected String decodeError(int error){   
  StringBuffer msg = new StringBuffer();   
  for(int j=1; j<ERR_16+1; j=j*2 ){
    if( (error&j)==j ){
      switch(j){
        case ERR_1:
          msg.append("error1");
          break;
        case ERR_4:
          msg.append("error4");
          break;
        case ERR_8:
          msg.append("error8");
          break;
        case ERR_16:
          msg.append("error16");
          break;
      }
    }   
  }   
  return msg.toString(); 
}
ERR_16 = 16; 
ERR_2 = 2; 
ERR_4 = 4; 
...

In case of error=-11, the function returns ERR_4. I know that & operator is bitwise AND operator but why someone should use it in this case?

3 Answers

Your error in binary (2-complement) is:

11111111111111111111111111110101

Because the left bit is a 1 your integer is negative and the second (2) and fourth(8) bit are set to 0, this brings your int to the value -(1+2+8) = -11

AND (&) is also known to be used as a Mask and in your example it would go like this:

Your loop values are:

1,2,4,8,16

11111111111111111111111111110101 & 00000000000000000000000000000001 == 1

11111111111111111111111111110101 & 00000000000000000000000000000010 == 0

11111111111111111111111111110101 & 00000000000000000000000000000100 == 4

11111111111111111111111111110101 & 00000000000000000000000000001000 == 0

11111111111111111111111111110101 & 00000000000000000000000000010000 == 16

Meaning you would get the outputs

error1, error4 and error16

This means you extracted multiple errors out of a single integer

every Bit stands for another error and with the masking (AND) you check which ones are stored in your integer

It's used to allow you to store several error flags in a single int; it's more of a C axiom.

The individual ERR_XX values represent the bit that is set for the corresponding error flag (eg, ERR_4 = 00000100). If several bits are set, there are several errors in place, eg 00001100 is ERR_4 and ERR_8. To check if a bit is set, it's ANDed; 00001100 AND ERR_4 == 00000100. The for loop goes through the possible ERRs by multiplying by 2 every loop.

Is this more understandable?

protected String decodeError(int error){   
  StringBuffer msg = new StringBuffer();
  if ((error & ERR_1) != 0)
    msg.append("error1");
  if ((error & ERR_4) != 0)
    msg.append("error4");
  if ((error & ERR_8) != 0)
    msg.append("error8");
  if ((error & ERR_16) != 0)
    msg.append("error16");
  return msg.toString();
}
Related