bit masking tricks

Solutions on MaxInterview for bit masking tricks by the best coders in the world

showing results for - "bit masking tricks"
Juan Esteban
03 Nov 2018
1Setting a bit
2Use the bitwise OR operator (|) to set a bit.
3
4number |= 1UL << n;
5That will set the nth bit of number. n should be zero, if you want to set the 1st bit and so on upto n-1, if you want to set the nth bit.
6
7Use 1ULL if number is wider than unsigned long; promotion of 1UL << n doesn't happen until after evaluating 1UL << n where it's undefined behaviour to shift by more than the width of a long. The same applies to all the rest of the examples.
8
9Clearing a bit
10Use the bitwise AND operator (&) to clear a bit.
11
12number &= ~(1UL << n);
13That will clear the nth bit of number. You must invert the bit string with the bitwise NOT operator (~), then AND it.
14
15Toggling a bit
16The XOR operator (^) can be used to toggle a bit.
17
18number ^= 1UL << n;
19That will toggle the nth bit of number.
20
21Checking a bit
22You didn't ask for this, but I might as well add it.
23
24To check a bit, shift the number n to the right, then bitwise AND it:
25
26bit = (number >> n) & 1U;
27That will put the value of the nth bit of number into the variable bit.
28
29Changing the nth bit to x
30Setting the nth bit to either 1 or 0 can be achieved with the following on a 2's complement C++ implementation:
31
32number ^= (-x ^ number) & (1UL << n);
33Bit n will be set if x is 1, and cleared if x is 0. If x has some other value, you get garbage. x = !!x will booleanize it to 0 or 1.
34
35To make this independent of 2's complement negation behaviour (where -1 has all bits set, unlike on a 1's complement or sign/magnitude C++ implementation), use unsigned negation.
36
37number ^= (-(unsigned long)x ^ number) & (1UL << n);
38or
39
40unsigned long newbit = !!x;    // Also booleanize to force 0 or 1
41number ^= (-newbit ^ number) & (1UL << n);
42It's generally a good idea to use unsigned types for portable bit manipulation.
43
44or
45
46number = (number & ~(1UL << n)) | (x << n);
47(number & ~(1UL << n)) will clear the nth bit and (x << n) will set the nth bit to x.
48
49It's also generally a good idea to not to copy/paste code in general and so many people use preprocessor macros (like the community wiki answer further down) or some sort of encapsulation.
similar questions
queries leading to this page
bit masking tricks