C program to set nth bit of a number

Write a C program to input any number from user and set nth bit of the given number as 1. How to set nth bit of a given number using bitwise operator in C programming. Setting nth bit of a given number using bitwise operator.



Input number: 12
Input nth bit to set: 0


Number after setting nth bit: 13 in decimal

Required knowledge

Basic C programming, Bitwise operator

Logic to set nth bit of a number

In my previous post I explained how easily to get nth bit value of any number using bitwise right shift and bitwise AND operator. To set any bit we use bitwise OR | operator.
Bitwise OR | operator evaluates each bit of the result to 1 if any of the operand's corresponding bit is set (1). In-order to set nth bit of a number we need to shift 1 n times to its right and then perform bitwise OR operation with the number and result of right shift performed just before. In general (1 << n) | number.

Program to set nth bit of a number

 * C program to set the nth bit of a number

#include <stdio.h>

int main()
    int num, n, newNum;

    // Input a number from user
    printf("Enter any number: ");
    scanf("%d", &num);

    // Input the bit number you want to set
    printf("Enter nth bit to set (0-31): ");
    scanf("%d", &n);

    // Right shift 1 to n times and perform bitwise OR with number
    newNum = (1 << n) | num;

    printf("Bit set successfully.\n\n");
    printf("Number before setting %d bit: %d (in decimal)\n", n, num);
    printf("Number after setting %d bit: %d (in decimal)\n", n, newNum);

    return 0;

Note: Here I have assumed that bit ordering starts from 0.


Enter any number: 12
Enter nth bit to set (0-31): 0
Bit set successfully.

Number before setting 0 bit: 12 (in decimal)
Number after setting 0 bit: 13 (in decimal)

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>