-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexp-2-6.c
40 lines (32 loc) · 939 Bytes
/
exp-2-6.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*************************************************************************
> File Name: exp-2-6.c
> Author: xiaoxiaoh
> Mail: [email protected]
> Created Time: Wed Jun 28 11:25:08 2017
************************************************************************/
/*
* Write a C program to toggle nth bit of a number.
*
* Example:
*
* Input number: 22
* Input nth bit to toggle: 1
*
* Output after toggling nth bit: 20 (in decimal)
*
*/
#include <stdio.h>
int main()
{
int num, n, newNum;
/* Read a number from user */
printf("Enter a number: ");
scanf("%d", &num);
/* Read the bit number you want to toggle */
printf("Enter the bit number you want to toggle: ");
scanf("%d", &n);
/* Left shift 1 to n times, then perform bitwise XOR with number and result of above */
newNum = num ^ (1 <<n );
printf("After toggling %dth bit, the original number %d ==> %d.\n", n, num, newNum);
return 0;
}