Bitwise Operators

This will cover bitwise operations and examples of their usages in C. These operations are extremely fast as CPUs are built with processors meant to do these operations directly without having to calculate multiple conditionals for each bit. A 64-bit processor can do these operations on a 64-bit number in a single operation, likewise a 32-bit processor can do these operations on a 32-bit number with a single operation.

OperatorSymbol
AND&
OR|
NOT
XOR
Left Shift<<
Right Shift>>

AND

Operator: Ampersand (&)
Syntax: ``

Takes two inputs applying the Logical AND to each pair of corresponding bits in the input.

int a = 7; //0111
int b = 9; //1001
int aANDb = a & b; //0001 or 1

OR

Operator: Pipe (|)
Syntax:

Takes two inputs applying the Logical OR to each pair of corresponding bits in the input.

int a = 7; //0111
int b = 9; //1001
int aORb = a | b; //1111 or 15

NOT

Operator: Tilde (~)
Syntax: ~value

Simply applies the Logical NOT to each bit in the input. This operation takes only a single input making it a Unary Operation.

int a = 7; //0111
int b = ~A; //1000 or 8

XOR

Operator: Caret (^)
Syntax: val1 ^ val2

Takes two inputs applying the Logical XOR to each pair of corresponding bits in the input.

int a = 7; //0111
int b = 9; //1001
int aXORb = a ^ b; //1110 or 14

Bitshift Operations

Bitshift operations move all the bits in a number left or right by a certain amount. They only work on integers, and the value of amount should always be positive.

Left Shift

Operator: <<
Syntax: value << amount

Functionality:

  • Shifts all the bits in the value to the left by the number of positions specified by amount.
  • The bits shifted out on the left side are discarded.
  • zero is filled in on the least significant bit position (rightmost bit).
    Effect:
  • Effectively multiplies the value by 2 raised to the power of amount.
int a = 10; //00001010
int amount = 2;
int shifted = a << amount; //00101000 or 40

Right Shift

Operator: >>
Syntax: value >> amount

Functionality:

  • Shifts all the bits in the value to the right by the number of positions specified by amount.
  • The bits shifted out on the right side are discarded.
  • The behavior for filling the leftmost bit position (depending on the data type):
    - Unsigned integers: Filled with zeros.
    - Signed integers: The sign bit (leftmost bit) is replicated to fill the empty positions. This preserves the sign of the original number for positive or negative values.
    Effect:
  • Effectively divides the value by 2 raised to the power of amount (performs an integer division, discarding any remainder).
int a = 40; //00101000
int amount = 2;
int shifted = a >> amount; //00001010 or 10