Bit Masking

Bit Masking is a technique used in computer programming to manipulate specific bits of a number. It involves the use of bitwise operators (AND, OR, XOR, NOT) to modify, set, clear, or test individual bits within a binary number. Bit Masking is commonly used in low-level programming, algorithms, and optimization tasks.

Here’s an explanation of common bit manipulation operations:

1. Setting a Bit

To set a specific bit (change it to 1), you can use the OR operator |.

1
2
3
int number = 5;  // Binary: 0101
int mask = 1 << 2; // Create mask to set the 2nd bit: 0100
number = number | mask; // Result: 0111 (7 in decimal)

2. Clearing a Bit

To clear a specific bit (change it to 0), you can use the AND operator & with a mask where all bits are set except the one you want to clear.

1
2
3
int number = 7;  // Binary: 0111
int mask = ~(1 << 2); // Create mask to clear the 2nd bit: 1011
number = number & mask; // Result: 0011 (3 in decimal)

3. Toggling a Bit

To toggle a specific bit (flip it), you can use the XOR operator ^.

1
2
3
int number = 5;  // Binary: 0101
int mask = 1 << 2; // Create mask to toggle the 2nd bit: 0100
number = number ^ mask; // Result: 0001 (1 in decimal)

4. Checking a Bit

To check whether a specific bit is set or not, you can use the AND operator &.

1
2
3
int number = 5;  // Binary: 0101
int mask = 1 << 2; // Create mask to check the 2nd bit: 0100
int result = number & mask; // Result: 0100 (4 in decimal), so the bit is set

5. Shifting Bits

Shifting bits left or right is done using the << and >> operators, respectively. Shifting can be used to multiply or divide by powers of 2, among other things.

1
2
3
int number = 5; // Binary: 0101
number = number << 1; // Left shift by 1: 1010 (10 in decimal)
number = number >> 2; // Right shift by 2: 0010 (2 in decimal)

Key Takeaways

  • Bit Masking involves manipulating individual bits within a binary number using bitwise operators.
  • Common operations include setting, clearing, toggling, checking, and shifting bits.
  • Bit Masking is used in a wide range of applications, from low-level hardware control to algorithm optimization, offering a fast and efficient way to handle binary data.