Bit Manipulation in Java: Get, Set, Clear & Update Bit Operations

Bit Manipulation in Java – Get, Set, Clear & Update Bit Operations

This tutorial covers bit manipulation fundamentals in Java, focusing on the four essential bit operations: Get, Set, Clear, and Update. These techniques are critical for optimizing algorithms, reducing time complexity, and are frequently asked in advanced placement and programming interviews. Understanding these operations builds on core Java concepts like Java Basics: Outputs, Variables, and User Input Explained and Mastering Java: Understanding Conditional Statements for Beginners.

Prerequisites: Left and Right Shift Operators

Before diving into bit manipulation, let's revise the left shift (<<) and right shift (>>) operators covered in the previous class.

| Operator | Description | Example | |----------|-------------|---------| | Left Shift (<<) | Shifts bits to the left, filling with zeros | 3 << 1 (binary 011110) = 6 | | Right Shift (>>) | Shifts bits to the right | 3 >> 1 (binary 011001) = 1 |

Format: number << positions or number >> positions

Understanding Bitmasking

Bitmasking is the process of performing operations on specific bits of a number using a bitmask – an additional number that isolates or targets particular bit positions.

The general process for all operations:

  1. Create a bitmask (1 left-shifted by the target position)
  2. Perform an operation (AND, OR, NOT) between the original number and the bitmask

1. Get Bit Operation

Purpose: Check if a specific bit at a given position is 1 or 0.

Example

  • Number: 5 (binary 0101)
  • Position: 2 (counting from right, 0-based)

Steps

  1. Create bitmask: 1 << position1 << 2 = 0100 (decimal 4)
  2. AND operation: 0101 & 0100 = 0100 (non-zero)
  3. Result: Non-zero means bit is 1; zero means bit is 0

Logic

  • The bitmask has only one 1 at the target position
  • AND with original number: if original also has 1 at that position → output is non-zero; otherwise zero

Code

int getBit(int num, int pos) {
    int bitMask = 1 << pos;
    return (num & bitMask) == 0 ? 0 : 1;
}

2. Set Bit Operation

Purpose: Set a specific bit to 1 (make it 1 regardless of its current value). This operation is a practical application of Understanding Java Short Circuit Operations: A Comprehensive Guide.

Example

  • Number: 5 (binary 0101)
  • Position: 1 → Output should be binary 0111 (decimal 7)

Steps

  1. Create bitmask: 1 << 1 = 0010
  2. OR operation: 0101 | 0010 = 0111 → decimal 7

Logic

  • OR with bitmask ensures target position becomes 1
  • Other bits remain unchanged (OR with 0 keeps original value)

Code

int setBit(int num, int pos) {
    int bitMask = 1 << pos;
    return num | bitMask;
}

3. Clear Bit Operation

Purpose: Clear (set to 0) a specific bit while keeping other bits unchanged.

Example

  • Number: 5 (binary 0101)
  • Position: 2 → Output should be binary 0001 (decimal 1)

Steps

  1. Create bitmask: 1 << 2 = 0100
  2. Negate the mask: ~0100 = 1011
  3. AND operation: 0101 & 1011 = 0001 → decimal 1

Logic

  • Negated mask has 0 only at the target position, 1s everywhere else
  • AND with original: target bit becomes 0 (since 0 AND anything = 0), other bits stay same (since 1 AND original bit = original bit)

Code

int clearBit(int num, int pos) {
    int bitMask = 1 << pos;
    return num & (~bitMask);
}

4. Update Bit Operation

Purpose: Update a bit to a desired value (0 or 1) at a specific position.

This operation combines Set and Clear:

  • To update to 1 → use Set operation
  • To update to 0 → use Clear operation

Example 1: Update to 1

  • Number: 5 (binary 0101)
  • Position: 2, Desired value: 1
  • Result: Binary 01010101 (already 1)
    • Use Set operation: 0101 | 0100 = 0101

Example 2: Update to 0

  • Number: 5 (binary 0101)
  • Position: 2, Desired value: 0
  • Result: Binary 01010001 (decimal 1)
    • Use Clear operation: 0101 & ~0100 = 0001

Code

int updateBit(int num, int pos, int op) {
    // op = 1 means set, op = 0 means clear
    int bitMask = 1 << pos;
    if (op == 1) {
        return num | bitMask;
    } else {
        return num & (~bitMask);
    }
}

Summary Table

| Operation | Purpose | Formula | |-----------|---------|---------| | Get | Check bit value (0 or 1) | (num & (1<<pos)) != 0 | | Set | Set bit to 1 | num | (1<<pos) | | Clear | Set bit to 0 | num & ~(1<<pos) | | Update | Set bit to desired value | Use Set or Clear based on desired value |

Key Takeaways

  1. Always create bitmask first: 1 << position
  2. Get bit uses AND to isolate the bit; check if result is non-zero
  3. Set bit uses OR to force the bit to 1
  4. Clear bit uses AND with negated mask to force the bit to 0
  5. Update bit is a combination of Set or Clear based on the target value
  6. Understanding logic is more important than memorization – especially for coding interviews where you may need to adapt techniques

These bit manipulation operations are foundational for many advanced topics in DSA, including:

  • Finding unique elements in arrays
  • Checking power of two
  • Counting set bits
  • Subset generation
  • Optimizing space in Boolean arrays

Practice these concepts with different numbers and positions to build strong intuition for bit-level programming.

For a deeper understanding of data types and memory, refer to the Comprehensive Guide to Integer Data Types and Modifiers in C Programming. To see how similar concepts apply in Python, check out Understanding Number Systems and Binary Conversion in Python.

Keep this summary

Save it to LunaNotes and it becomes a real note in your library — editable, searchable, and ready to turn into flashcards or a diagram. Free to start.

Save to LunaNotes

Or summarise for another video.

This summary and transcript were automatically generated using AI with the Free YouTube Transcript Summary Tool by LunaNotes.

Related summaries

Bit Manipulation in Java: Get, Set, Clear, and Update Bit Operations Explained

Bit Manipulation in Java: Get, Set, Clear, and Update Bit Operations Explained

Learn the four fundamental bit manipulation operations in Java: Get Bit, Set Bit, Clear Bit, and Update Bit. This comprehensive tutorial covers creating bitmasks using left shift, performing AND/OR operations, and applying bitwise NOT for clear operations, with practical code examples in Java.

Understanding Java Short Circuit Operations: A Comprehensive Guide

Understanding Java Short Circuit Operations: A Comprehensive Guide

Explore Java short circuit operations, including examples and benefits for improved performance in programming.

Understanding Number Systems and Binary Conversion in Python

Understanding Number Systems and Binary Conversion in Python

This video tutorial explains the fundamentals of various number systems including binary, octal, decimal, and hexadecimal, focusing on their significance in programming. Learn how to convert decimal numbers to binary using Python's built-in functions and understand manual conversion techniques for accuracy and better comprehension. Practical examples and homework exercises enhance your grasp on number system conversions essential for programming tasks such as working with IP addresses and bitwise operations.

Mastering Java: Understanding Conditional Statements for Beginners

Mastering Java: Understanding Conditional Statements for Beginners

Dive into Java's conditional statements, including 'if', 'switch', and 'break', to enhance your programming skills.

Understanding Operators in C Programming: Types and Applications

Understanding Operators in C Programming: Types and Applications

This lecture introduces the concept of operators in C programming, explaining their essential role in performing calculations, comparisons, and logical decisions. It covers various categories of operators including arithmetic, relational, logical, bitwise, increment/decrement, assignment, and others, with practical examples illustrating their use.

Found this summary useful?

Take it with you. One click puts it in your own LunaNotes library.

Save to LunaNotes

Start taking better notes today with LunaNotes