 FeedbackArticles

# BIT MANIPULATION

Bit manipulation is a technique used in computer programming to manipulate individual bits of a binary number. It is typically used to optimize memory utilization and to perform fast arithmetic operations.

A binary number is a number expressed in base-2, where each digit is either a 0 or a 1. Bit manipulation is used to manipulate these individual 0s and 1s to perform various operations.

Some common bit manipulation operations include:

• Bitwise AND (&): Takes two binary numbers and performs an AND operation on each corresponding bit. If both bits are 1, the result is 1. Otherwise, the result is 0.
• Bitwise OR (|): Takes two binary numbers and performs an OR operation on each corresponding bit. If either bit is 1, the result is 1. Otherwise, the result is 0.
• Bitwise XOR (^): Takes two binary numbers and performs an XOR operation on each corresponding bit. If the bits are the same, the result is 0. If the bits are different, the result is 1.
• Bitwise NOT (~): Takes a single binary number and performs a NOT operation on each bit. Each 0 is replaced with a 1, and each 1 is replaced with a 0.
• Bitwise left shift (<<): Takes a binary number and shifts each bit to the left by a specified number of positions. Zeros are shifted in from the right.
• Bitwise right shift (>>): Takes a binary number and shifts each bit to the right by a specified number of positions. Zeros are shifted in from the left.

Bit manipulation can be used to perform a wide variety of tasks, including:

• Checking if a particular bit is set in a number.
• Setting a particular bit in a number.
• Clearing a particular bit in a number.
• Flipping a particular bit in a number.
• Extracting a particular set of bits from a number.
• Combining two numbers by setting the bits of one number in another.
• Performing arithmetic operations on binary numbers, such as addition and multiplication.