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.

Example

Input

Input number: 12
Input nth bit to set: 0

Output

Number after setting nth bit: 13 in decimal

Also read – Program to get nth bit of a number

Required knowledge

Bitwise operators, Data types, Variables and Expressions, Basic input/output

Logic to set nth bit of a number

We use bitwise OR | operator to set any bit of a number. Bitwise OR operator evaluate each bit of the resultant value to 1 if any of the operand corresponding bit is 1.

Step by step descriptive logic to set nth bit of a number.

  1. Input number from user. Store it in some variable say num.
  2. Input bit position you want to set. Store it in some variable say n.
  3. To set a particular bit of number. Left shift 1 n times and perform bitwise OR operation with num. Which is newNum = (1 << n) | num;.

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 number from user */
    printf("Enter any number: ");
    scanf("%d", &num);

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

    /* Left shift 1, n times and perform bitwise OR with num */
    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;
}

Output

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 😉