Skip to main content
Engineering LibreTexts

4.4: Bitwise Operations

  • Page ID
    35815
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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
    

    This page titled 4.4: Bitwise Operations is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by James M. Fiore via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.