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

Written by

Garvit Gulati

Given a number num and a value n, we have to set the value of nth bit from right in the binary representation of that number.

Introduction to Left shift and Right shift operator

  • The left shift and right shift operators are used to shift the bits of a number either left or right as specified.
  • RIGHT SHIFT(>>): it accepts to numbers, and shifts the first number to the right, number of times as specified by the second number. For example,
  • Shifting a number to left n times, is equivalent to multiplying the number by 2n.


# Approaching the problem

Setting nth bit of a number means assigning the value 1 to its nth bit if it was 0 and if 1 leaving it as it is.

To set the nth bit of  a number we have to operate it with a number such that it edits only the nth bit of that number.

Since we have to turn it to 1 if its zero and leave it as it is if its 1, its clear that we have to perform an OR operation with a number that has 1 at the nth bit. Rest of the bits should be zero so that it doesn’t change any other bit. The number will be obtained by shifting 1 to the right by n-1 times.

For example, we have to set 2nd bit 13

13 1 1 0 1
1>>(n-1) 0 0 1 0
OR 1 1 1 1 =15




# Algorithm

  1. Input num and n from the user
  2. Right shift 1, n-1 times
  3. Take its OR with num



#include <iostream>
using namespace std;

int main()

{ int num, n;

cout &lt;&lt; "Enter number\n";

cin &gt;&gt; num;

cout &lt;&lt; "Enter bit number you wish to set\n";

cin &gt;&gt; n;

cout &lt;&lt; "Bit set Successfully\n";

cout &lt;&lt; "Answer:" &lt;&lt; (num | (1 &lt;&lt; (n - 1)));



Enter Number

Enter bit number you wish to set 2

Bit set Successfully Answer: 15