Swap all odd and even bits

14 Feb, 2022
Given an unsigned integer, swap all odd bits with even bits. For example, if the given number is 23 (00010111), it should be converted to 43 (00101011). Every even position bit is swapped with adjacent bit on right side (even position bits are highlighted in binary representation of 23), and every odd position bit is swapped with adjacent on left side. 
It is very hard to remember  0xAAAAAAAA as a number of 32 bit which is set at all even bits and 0x55555555  as a number of 32 bit which is set at all odd bits. So there is another solution for this. Here we need to perform operation in a brute force manner. 
Find bit of i  and i+1.To swap the bits subtract and add corresponding values.To remove bit at ith bit to i+1. we need to subtract i_bit<<i and add it at i+1 location for that we need to add i_bit<<(i+1).Similarly do for (i+1)th bit. Remove it from i+1 to i.
Find bit of i  and i+1.
To swap the bits subtract and add corresponding values.
To remove bit at ith bit to i+1. we need to subtract i_bit<<i and add it at i+1 location for that we need to add i_bit<<(i+1).
Similarly do for (i+1)th bit. Remove it from i+1 to i.
C++
Java
Python3
C#
Javascript
// C++ program to swap even and// odd bits of a given number#include <bits/stdc++.h>using namespace std; // Function to swap even// and odd bitsunsigned int swapBits(unsigned int x){    for(int i=0; i<32; i+=2){        int i_bit = ( x >> i ) & 1; // find i th bit        int i_1_bit = (x >> ( i+1 )) & 1;  // find i+1 th bit                 x = x - ( i_bit << i) // remove i_bit              - ( i_1_bit << ( i+1 ) ) // remove i+1 th bit              + ( i_bit << ( i+1 ) ) // put i_bit at i+1 location              + ( i_1_bit << i );  // put i+1 bit at i location    }    return x;} // Driver codeint main(){    unsigned int x =23; // 00010111     // Output is 43 (00101011)    cout<<swapBits(x);     return 0;} // This code is contributed by Amandeep Gupta
// Java program to swap even and// odd bits of a given numberimport java.io.*; class GFG {     // Function to swap even    // and odd bits    static int swapBits(int x)    {        for (int i = 0; i < 32; i += 2) {            int i_bit = (x >> i) & 1; // find i th bit            int i_1_bit                = (x >> (i + 1)) & 1; // find i+1 th bit             x = x - (i_bit << i) // remove i_bit                - (i_1_bit << (i + 1)) // remove i+1 th bit                + (i_bit                   << (i + 1)) // put i_bit at i+1 location                + (i_1_bit                   << i); // put i+1 bit at i location        }        return x;    }     // Driver code    public static void main(String[] args)    {        int x = 23; // 00010111         // Output is 43 (00101011)        System.out.print(swapBits(x));    }} // This code is contributed by subham348.
# Python program to swap even and# odd bits of a given number # Function to swap even# and odd bitsdef swapBits(x):       # Get all even bits of x    even_bits = x & 0xAAAAAAAA     # Get all odd bits of x    odd_bits = x & 0x55555555         # Right shift even bits    even_bits >>= 1         # Left shift odd bits    odd_bits <<= 1    for i in range(0,32,2):        i_bit = (x >> 1) & 1; # find i th bit        i_1_bit = (x >> (i + 1)) & 1; # find i+1 th bit                 x = x - (i_bit << i) # remove i_bit        - (i_1_bit << (i + 2)) # remove i+1 th bit        + (i_bit << (i + 1)) # put i_bit at i+1 location        + (i_1_bit << i); # put i+1 bit at i location         # Combine even and odd bits    return (even_bits | odd_bits) # Driver codeif __name__ == '__main__':    x = 23; # 00010111     # Output is 43 (00101011)    print(swapBits(x));  # This code is contributed by Rajput-Ji
// C# program to swap even and// odd bits of a given numberusing System; class GFG {     // Function to swap even    // and odd bits    static int swapBits(int x)    {        for (int i = 0; i < 32; i += 2) {            int i_bit = (x >> i) & 1; // find i th bit            int i_1_bit                = (x >> (i + 1)) & 1; // find i+1 th bit             x = x - (i_bit << i) // remove i_bit                - (i_1_bit << (i + 1)) // remove i+1 th bit                + (i_bit                   << (i + 1)) // put i_bit at i+1 location                + (i_1_bit                   << i); // put i+1 bit at i location        }        return x;    }     // Driver code    public static void Main()    {        int x = 23; // 00010111         // Output is 43 (00101011)        Console.Write(swapBits(x));    }} // This code is contributed by subham348.
<script>// JavaScript Program to implement// the above approach // Function to swap even// and odd bitsfunction swapBits( x){    for(let i = 0; i < 32; i += 2){        let i_bit = ( x >> i ) & 1; // find i th bit        let i_1_bit = (x >> ( i+1 )) & 1;  // find i+1 th bit                 x = x - ( i_bit << i) // remove i_bit              - ( i_1_bit << ( i+1 ) ) // remove i+1 th bit              + ( i_bit << ( i+1 ) ) // put i_bit at i+1 location              + ( i_1_bit << i );  // put i+1 bit at i location    }    return x;} // Driver code    let x =23; // 00010111     // Output is 43 (00101011)    document.write(swapBits(x));     // This code is contributed by Potta Lokesh    </script>
Output: 
 43 
Time Complexity: O(constant)
Auxiliary Space: O(1)
If we take a closer look at the example, we can observe that we basically need to right shift (>>) all even bits (In the above example, even bits of 23 are highlighted) by 1 so that they become odd bits (highlighted in 43), and left shift (<<) all odd bits by 1 so that they become even bits. The following solution is based on this observation. The solution assumes that input number is stored using 32 bits.Let the input number be x 1) Get all even bits of x by doing bitwise and of x with 0xAAAAAAAA. The number 0xAAAAAAAA is a 32 bit number with all even bits set as 1 and all odd bits as 0. 2) Get all odd bits of x by doing bitwise and of x with 0x55555555. The number 0x55555555 is a 32 bit number with all odd bits set as 1 and all even bits as 0. 3) Right shift all even bits. 4) Left shift all odd bits. 5) Combine new even and odd bits and return.  
C++
C
Java
Python 3
C#
PHP
Javascript
// C++ program to swap even and// odd bits of a given number#include <bits/stdc++.h>using namespace std; // Function to swap even// and odd bitsunsigned int swapBits(unsigned int x){    // Get all even bits of x    unsigned int even_bits = x & 0xAAAAAAAA;     // Get all odd bits of x    unsigned int odd_bits = x & 0x55555555;     even_bits >>= 1; // Right shift even bits    odd_bits <<= 1; // Left shift odd bits     return (even_bits | odd_bits); // Combine even and odd bits} // Driver codeint main(){    unsigned int x = 23; // 00010111     // Output is 43 (00101011)    cout<<swapBits(x);     return 0;} // This code is contributed by rathbhupendra
// C program to swap even and// odd bits of a given number#include <stdio.h> // Function to swap even// and odd bitsunsigned int swapBits(unsigned int x){    // Get all even bits of x    unsigned int even_bits = x & 0xAAAAAAAA;     // Get all odd bits of x    unsigned int odd_bits  = x & 0x55555555;     even_bits >>= 1;  // Right shift even bits    odd_bits <<= 1;   // Left shift odd bits     return (even_bits | odd_bits); // Combine even and odd bits} // Driver program to test above functionint main(){    unsigned int x = 23; // 00010111     // Output is 43 (00101011)    printf("%u ", swapBits(x));     return 0;}
// Java program to swap even// and odd bits of a given number class GFG{         // Function to swap even    // and odd bits    static int swapBits(int x)    {        // Get all even bits of x        int even_bits = x & 0xAAAAAAAA;             // Get all odd bits of x        int odd_bits = x & 0x55555555;             // Right shift even bits        even_bits >>= 1;                 // Left shift even bits        odd_bits <<= 1;                 // Combine even and odd bits        return (even_bits | odd_bits);    }         // Driver program to test above function    public static void main(String[] args)    {        int x = 23; // 00010111             // Output is 43 (00101011)        System.out.println(swapBits(x));    }} // This code is contributed by Smitha Dinesh Semwal
# Python 3 program to swap even# and odd bits of a given number # Function for swapping even# and odd bitsdef swapBits(x) :         # Get all even bits of x    even_bits = x & 0xAAAAAAAA     # Get all odd bits of x    odd_bits = x & 0x55555555         # Right shift even bits    even_bits >>= 1         # Left shift odd bits    odd_bits <<= 1     # Combine even and odd bits    return (even_bits | odd_bits)  # Driver program# 00010111x = 23 # Output is 43 (00101011)print(swapBits(x))  # This code is contributed# by Nikita Tiwari.
// C# program to swap even and odd bits// of a given numberusing System; class GFG {         // Function to swap even    // and odd bits    static long swapBits(int x)    {        // Get all even bits of x        long even_bits = x & 0xAAAAAAAA;             // Get all odd bits of x        long odd_bits = x & 0x55555555;             // Right shift even bits        even_bits >>= 1;                 // Left shift even bits        odd_bits <<= 1;                 // Combine even and odd bits        return (even_bits | odd_bits);    }         // Driver program to test above function    public static void Main()    {                 int x = 23; // 00010111             // Output is 43 (00101011)        Console.Write(swapBits(x));    }} // This code is contributed by Sam007.
<?php// PHP program to swap even and// odd bits of a given number // Function to swap even// and odd bitsfunction swapBits( $x){         // Get all even bits of x    $even_bits = $x & 0xAAAAAAAA;     // Get all odd bits of x    $odd_bits = $x & 0x55555555;         // Right shift even bits    $even_bits >>= 1;         // Left shift odd bits    $odd_bits <<= 1;     // Combine even and odd bits    return ($even_bits | $odd_bits);} // Driver Code // 00010111$x = 23; // Output is 43 (00101011)echo swapBits($x); // This code is contributed by Ajit?>
<script>// java script program to swap even and// odd bits of a given number // Function to swap even// and odd bitsfunction swapBits( x){         // Get all even bits of x    even_bits = x & 0xAAAAAAAA;     // Get all odd bits of x    odd_bits = x & 0x55555555;         // Right shift even bits    even_bits >>= 1;         // Left shift odd bits    odd_bits <<= 1;     // Combine even and odd bits    return (even_bits | odd_bits);} // Driver Code // 00010111let x = 23; // Output is 43 (00101011)document.write(swapBits(x)); // This code is contributed by sravan kumar </script>
Output: 
 43 
Time Complexity: O(1)
Auxiliary Space: O(1) 
Swap all odd and even bits | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersSwap all odd and even bits | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:32•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=GWLCF808oVI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
jit_t
rathbhupendra
sravankumar8128
indianamandeep2001
subham348
lokeshpotta20
Rajput-Ji
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.