TutorialStudyMite

Program to set Nth bit of a number in C++

GGarvit Gulati5 min read
Beginner friendly

Try it first

Set Nth Bit

Give it a try before seeing the solution in this article.

Give it a try

Track completion, mastery, and revision.

Given a number num and a bit position n, the task is to set the nth bit (from the right, 1-indexed) in the binary representation of num to 1. If the nth bit is already 1, it remains 1; if it's 0, it becomes 1. This operation is fundamental in bit manipulation and is frequently used in low-level programming and algorithm optimization.

Understanding Bitwise OR (|)

The bitwise OR operator (|) compares corresponding bits of two operands. If either bit is 1, the resulting bit is 1. Otherwise, if both bits are 0, the resulting bit is 0.

Here's a truth table for the OR operation:

| Bit 1 | Bit 2 | Result (Bit 1 | Bit 2) | | :---- | :---- | :-------------------- | | 0 | 0 | 0 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 1 |

Key Property for Setting Bits: When you OR a bit with 1, the result is always 1. When you OR a bit with 0, the result is the original bit. This property is exactly what we need to set a specific bit without affecting others.

The Left Shift Operator (<<)

The left shift operator (<<) shifts the bits of a number to the left by a specified number of positions. For every position shifted, a 0 is appended to the rightmost end.

Syntax: number << positions

Example: If num = 1 (binary 0001) and we shift it left by 2 positions: 1 << 2 results in 4 (binary 0100).

Original: 0001 (1)
Shift left by 1: 0010 (2)
Shift left by 2: 0100 (4)

Shifting a number x to the left by n positions is equivalent to multiplying x by 2^n.

Approaching the Problem: Setting the Nth Bit

To set the nth bit of a number, we need to perform a bitwise OR operation with a special "mask" number. This mask should have only its nth bit set to 1, with all other bits being 0.

Why this works:

  • When we OR num with the mask, the nth bit of num will be ORed with 1 (from the mask), guaranteeing the result for that position is 1.
  • All other bits of num will be ORed with 0 (from the mask), which means they will retain their original values.

Creating the Bitmask

Given that n is 1-indexed (e.g., n=1 for the rightmost bit, n=2 for the second bit from the right), we can create the required mask by left-shifting the number 1 by n-1 positions.

  • To set the 1st bit (n=1): 1 << (1-1) which is 1 << 0 (binary ...0001)
  • To set the 2nd bit (n=2): 1 << (2-1) which is 1 << 1 (binary ...0010)
  • To set the 3rd bit (n=3): 1 << (3-1) which is 1 << 2 (binary ...0100)

Combining for the Solution

Once we have the mask (1 << (n - 1)), we simply perform a bitwise OR operation with our original number num:

result = num | (1 << (n - 1))

Example Walkthrough

Let's say we want to set the 2nd bit (n=2) of the number 13.

  1. Binary representation of num = 13:

    ...01101
    
  2. Calculate the mask for the 2nd bit (n=2): mask = 1 << (n - 1) mask = 1 << (2 - 1) mask = 1 << 1 mask = 2 (binary ...00010)

  3. Perform the bitwise OR operation: num | mask

      num:  ...01101  (13)
    mask:   ...00010  (2)
    ------------------
    Result: ...01111  (15)
    

    As you can see, the 2nd bit (from the right) of 13 was 0, and after the operation, it became 1. The other bits remained unchanged. The new number is 15.

Algorithm to Set Nth Bit

  1. Prompt the user to enter an integer value and store it in a variable, num.
  2. Prompt the user to enter the position of the bit they wish to set (n, 1-indexed) and store it in a variable.
  3. Calculate the bitmask by left-shifting 1 by n-1 positions: mask = (1 << (n - 1)).
  4. Perform a bitwise OR operation between num and mask: result = num | mask.
  5. Print the result to the console.

C++ Program

#include <iostream> // Required for input/output operations

int main() {
    int num; // Variable to store the input number
    int n;   // Variable to store the bit position to set (1-indexed)

    // Prompt user for the number
    std::cout << "Enter an integer number: ";
    std::cin >> num;

    // Prompt user for the bit position
    std::cout << "Enter the bit number (1-indexed from right) you wish to set: ";
    std::cin >> n;

    // Validate input for n (optional, but good practice)
    if (n <= 0 || n > (sizeof(int) * 8)) { // Assuming int is 32-bit, max n=32
        std::cout << "Invalid bit number. Please enter a positive integer within the range of int bits." << std::endl;
        return 1; // Indicate an error
    }

    // Calculate the new number with the Nth bit set
    // (1 << (n - 1)) creates a mask with only the Nth bit set
    // The bitwise OR (|) operation sets the Nth bit of 'num'
    int result = num | (1 << (n - 1));

    std::cout << "Bit set successfully!" << std::endl;
    std::cout << "Original number: " << num << std::endl;
    std::cout << "Number with " << n << "th bit set: " << result << std::endl;

    return 0; // Indicate successful execution
}

Example Output

Enter an integer number: 13
Enter the bit number (1-indexed from right) you wish to set: 2
Bit set successfully!
Original number: 13
Number with 2th bit set: 15

Finished reading?

Was this helpful?

Your feedback shapes better tutorials for everyone.