-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbitOperation.txt
More file actions
33 lines (22 loc) · 902 Bytes
/
Copy pathbitOperation.txt
File metadata and controls
33 lines (22 loc) · 902 Bytes
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
http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c-c
Setting a bit
Use the bitwise OR operator (|) to set a bit.
number |= 1 << x;
That will set bit x.
Clearing a bit
Use the bitwise AND operator (&) to clear a bit.
number &= ~(1 << x);
That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.
Toggling a bit
The XOR operator (^) can be used to toggle a bit.
number ^= 1 << x;
That will toggle bit x.
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.
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.