Skip to content

Commit 9627944

Browse files
authored
Update Introduction.md
1 parent 30ca324 commit 9627944

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

src/com/deepak/algorithms/BitManipulation/Introduction.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,14 @@ So, if we do XOR against 111...1111, all the bits of myBits flipped. It's equiva
4242

4343
Another interesting trick using the XOR: It does in place swap of integers.
4444
If we apply the XOR operation twice -- say we have a bit, A, and another bit B, and we set C equal to A XOR B, and then take C XOR B: we get A XOR B XOR B, which essentially either flips every bit of A twice, or never flips the bit, so we just get back A. (We can also think of B XOR B as cancelling out.)
45+
46+
**Tricks with Bits**
47+
48+
**x & (x-1)** = will clear the lowest set bit of x.
49+
**x & ~(x-1)** = extracts the lowest set bit of x (all others are clear). Pretty patterns when applied to a linear sequence.
50+
**x & (x + (1 << n))** = x, with the run of set bits (possibly length 0) starting at bit n cleared.
51+
**x & ~(x + (1 << n))** = the run of set bits (possibly length 0) in x, starting at bit n.
52+
**x | (x + 1)** = x with the lowest cleared bit set.
53+
**x | ~(x + 1)** = extracts the lowest cleared bit of x (all others are set).
54+
**x | (x - (1 << n))** = x, with the run of cleared bits (possibly length 0) starting at bit n set.
55+
**x | ~(x - (1 << n))** = the lowest run of cleared bits (possibly length 0) in x, starting at bit n are the only clear bits.

0 commit comments

Comments
 (0)