Bitwise operations are one of the groovier features of C, C++, Java, and probably a dozen other languages.

Everything in a computer is just a long, long list of zeroes and ones. Ordinarily, you can only alter the bits one byte (eight bits) at a time (or two bytes at a time, or four, or nowadays eight). Bitwise operations let you mess with the individual bits themselves. It's fun, and it goes like this: You beat two integers against each other, and...

  • Bitwise OR: "|" If a given bit is "on" in either operand, or in both operands, the corresponding bit in the result will be "on":

    5 | 9 == 13
    
      0101    ==  5
    | 1001    ==  9
    ------ 
      1101    == 13
    
  • Bitwise AND: "&" If and only if a given bit is "on" in both operands, the corresponding bit in the result will be "on":

    5 & 9 == 1
      
      0101    == 5 
    & 1001    == 9 
    ------ 
      0001    == 1 
    
  • Bitwise exclusive OR (XOR): "^" If a given bit is "on" in one operand and not the other, the corresponding bit in the result will be "on":

    5 ^ 9 == 12
    
      0101    == 5
    ^ 1001    == 9
    ------
      1100    == 12
    
  • Bitwise complement: "~" This is an unary operator, which is to say that it takes only one operand. If a given bit in that one lonesome operand is "on", the corresponding bit in the result will be "off", and vice-versa (see also Obo):

    ~9 == 6
    
    ~ 1001    == 9
    ------ 
      0110    == 6
    

This is probably not as clear as it could be, but if you're trying to learn C from E2, umm, I got news for ya...




We thank Jamer for spotting a gruesome error in the XOR example.

Log in or register to write something here or to contact authors.