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
Output number after setting nth bit: 13 in decimal

Required knowledge:

Basic C programming, Bitwise operator


In my previous post I explained how easily we can get nth bit value of any number using bitwise right shift and bitwise AND operator. To set any bit we use bitwise OR | operator. As we already know 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.


 * C program to set the nth bit of a number

#include <stdio.h>

int main()
    int num, n, newNum;

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

    //Reads 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 ;)

Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment