Skip to main content
Engineering LibreTexts

4.4: Bitwise Operations

  • Page ID
  • Sometimes you’d like to perform bitwise operations rather than ordinary math. For example, what if you want to logically AND two variables, bit by bit? Bitwise operations are very common when programming microcontrollers as a means of setting, clearing and testing specific bits in control registers (for example, setting a specific pin on a digital port to read mode instead of write mode). C has a series of bitwise operators. They are:

    Table \(\PageIndex{1}\): Bitwise operators.
    & AND
    | OR
    ^ XOR
    ~ One’s Complement
    >> Shift Right
    << Shift Left

    Note the double use of & for “address of” and now AND. The unary operation is always “address of”, and the binary operation is always AND, so a & b would not imply the address of b. If you wanted to AND x with y, shift the result 2 places to the left and assign the result to z, you’d use:

    z = (x&y)<<2;

    Let’s look at a few examples. Suppose the variables X, Y and Z are unsigned chars. X and Y are set to 13 and 134, respectively. In hex, that’s 0x0d and 0x86 for bit patterns of 00001101 and 10000110.

    Z = X<<3;    // Z is 01101000 or 0x68
    Z = X>>1;    // Z is 00000110 or 0x06
    Z = ~X;      // Z is 11110010 or 0xf2
    Z = X|Y;     // Z is 10001111 or 0x8f
    Z = X&Y;     // Z is 00000100 or 0x04
    Z = X^Y;     // Z is 10001011 or 0x8b