Bitwise operations


Bitwise operators include:

& AND
&= AND
| OR
|= OR
^ XOR
^= XOR
~ one's compliment
<< Shift Left
<< Shift Left
>>= Shift Right
>>=Shift Right


AND OR and XOR

These require two operands and will perform bit comparisions.

AND & will copy a bit to the result if it exists in both operands.

  
  main()
  {
    unsigned int a = 60;	/* 60 = 0011 1100 */  
    unsigned int b = 13;	/* 13 = 0000 1101 */
    unsigned int c = 0;           

    c = a & b;                  /* 12 = 0000 1100 */ 
  }

OR | will copy a bit if it exists in eather operand.

  
  main()
  {
    unsigned int a = 60;	/* 60 = 0011 1100 */  
    unsigned int b = 13;	/* 13 = 0000 1101 */
    unsigned int c = 0;           

    c = a | b;                  /* 61 = 0011 1101 */ 
  }

XOR ^ copies the bit if it is set in one operand (but not both).

  
  main()
  {
    unsigned int a = 60;	/* 60 = 0011 1100 */  
    unsigned int b = 13;	/* 13 = 0000 1101 */
    unsigned int c = 0;           

    c = a ^ b;                  /* 49 = 0011 0001 */ 
  }

o XOR example program which swaps the contents of two variables.

Try it out with one of these simulators.

CGI simulator JavaScript Simulator


Ones Complement

This operator is unary (requires one operand) and has the efect of 'flipping' bits.


  main()
  {
    unsigned int Value=4;          /*   4 = 0000 0100 */  

    Value = ~ Value;               /* 251 = 1111 1011 */  

  }

Try it out

CGI simulator


Bit shift.

The following
operators can be used for shifting bits left or right.

<< >> <<= >>=

The left operands value is moved left or right by the number of bits specified by the right operand. For example:


  main()
  {
    unsigned int Value=4;          /*  4 = 0000 0100 */  
    unsigned int Shift=2;

    Value = Value << Shift;        /* 16 = 0001 0000 */  

    Value <<= Shift;               /* 64 = 0100 0000 */  

    printf("%d\n", Value);         /* Prints 64      */  
  }

Usually, the resulting 'empty' bit is assigned ZERO. Please use unsigned variables with these operators to avoid unpredictable results.

Try it out with one of these silulators

CGI simulator JavaScript Simulator


Examples:

AND
OR
Bit shifting.

Problem:

Bit shifting problem.

See Also:

All the other Expressions and operators.
Operator precedence.
Assignment Operators.

Top Master Index Keywords Functions


Martin Leslie