Skip to content

Commit ccf624e

Browse files
committed
feat(cpp): add swap_odd_and_even_bits.cpp
1 parent 2952f11 commit ccf624e

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
unsigned int swapOddAndEvenBits(unsigned int n) {
2+
unsigned int evenMask = 0x55555555; // 01010101010101010101010101010101
3+
unsigned int oddMask = 0xAAAAAAAA; // 10101010101010101010101010101010
4+
unsigned int evenBits = n & evenMask;
5+
unsigned int oddBits = n & oddMask;
6+
// Shift the even bits to the left, the odd bits to the right, and
7+
// merge these shifted values together.
8+
return (evenBits << 1) | (oddBits >> 1);
9+
}

0 commit comments

Comments
 (0)