-
Notifications
You must be signed in to change notification settings - Fork 0
/
bittoggle.c
74 lines (52 loc) · 1.69 KB
/
bittoggle.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <stdio.h>
void getBin(int num, char* str);
int main(int argc, char* args[]) {
char str[10];
long number = 0;
getBin(number, str);
printf("num is now: %s \n\n", str);
//Setting a bit
//Use the bitwise OR operator (|) to set a bit.
number |= 1 << 4;
//That will set bit x.
printf("4.th bit setted using |=");
getBin(number, str);
printf("num is now: %s \n\n", str);
//Clearing a bit
//Use the bitwise AND operator (&) to clear a bit.
number &= ~(1 << 4);
//That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.
printf("4.th bit cleared using &=");
getBin(number, str);
printf("num is now: %s \n\n", str);
//Toggling a bit
//The XOR operator (^) can be used to toggle a bit.
number ^= 1 << 6;
//That will toggle bit x.
printf("6.th bit toggled using ^=");
getBin(number, str);
printf("num is now: %s \n\n", str);
//Checking a bit
//You didn't ask for this but I might as well add it.
//To check a bit, shift the number x to the right, then bitwise AND it:
//bit = (number >> x) & 1;
//That will put the value of bit x into the variable bit.
//printf("4.th bit checked ");
//getBin(number, str);
//printf("num is now: %s \n\n", str);
//Changing the nth bit to x
//Setting the nth bit to either 1 or 0 can be achieved with the following:
//number ^= (-x ^ number) & (1 << n);
//Bit n will be set if x is 1, and cleared if x is 0.
//printf("4.th bit setted using |=");
//getBin(number, str);
//printf("num is now: %s \n\n", str);
return 0;
}
void getBin(int num, char *str)
{
*(str+5) = '\0';
int mask = 0x10 << 1;
while(mask >>= 1)
*str++ = !!(mask & num) + '0';
}