Bitwise Operator

A bitwise operator is an operator used to perform bitwise operations on bit patterns or binary numerals that involve the manipulation of individual bits.
Bitwise operators are used in:
  • Communication stacks where the individual bits in the header attached to the data signify important information
  • Embedded software for controlling different functions in the chip and indicating the status of hardware by manipulating the individual bits of hardware registers of embedded microcontrollers
  • Low-level programming for applications such as device drivers, cryptographic software, video decoding software, memory allocators, compression software and graphics
  • Maintaining large sets of integers efficiently in search and optimization problems
  • Bitwise operations performed on bit flags, which can enable an instance of enumeration type to store any combination of values defined in an enumerator list
Unlike common logical operators (like +, -, *), which work with bytes or groups of bytes, bitwise operators can check or set each of the individual bits within a byte. Bitwise operators never cause overflow because the result produced after the bitwise operation is within the range of possible values for the numeric type involved.
The bitwise operators used in the C family of languages (C#, C and C++) are:

  • OR (|): Result is true if any of the operands is true.
  • AND (&): Result is true only if both operands are true. It can be used to set up a mask to check the values of certain bits.
  • XOR (^): Result is true only if one of its operands is true. It is used mainly to toggle certain bits. It also helps to swap two variables without using a third one.
  • Bitwise Complement or Inversion or NOT (~): Provides the bitwise complement of an operand by inverting its value such that all zeros are turned into ones and all ones are turned to zeros.
  • >> (Right-Shift) and << (Left-Shift) Operator: Moves the bits the number of positions specified by the second operand in the right or left direction. While the right-shift operation is an arithmetic shift for operands of type int or long, it is a logical shift for operands of type uint or ulong. Shift operators are used in aligning bits.
The order of precedence (from highest to lowest) in bitwise operators is:
  1. ~
  2. << and >>
  3. &
  4. ^
  5. |
This definition was written in the context of General Programming

Post a Comment

0 Comments