Program Discussion :: Bitwise Operator
14 / 15
Write an efficient program to swap the odd and even bits in an integer
Answer:
#include
#include
using namespace std;
unsigned 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
Asked In ::
Language:
Rahul
7 Jul, 2017 9:30 AM
#include <stdio.h>
unsigned 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 function */
int main()
{
unsigned int x = 23; // 00010111
/* Output is 43 (00101011) */
printf("%u ", swapBits(x));
return 0;
}
Language:
Neha
7 Jul, 2017 9:30 AM
#include <stdio.h>
#include<iostream>
using namespace std;
unsigned 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 function
int main()
{
unsigned int x = 23; // 00010111
// Output is 43 (00101011)
cout<<swapBits(x);
return 0;
}
Language:
Yash
11 Jun, 2018 2:45 AM
// C program to swap even and
// odd bits of a given number
#include <stdio.h>
// Function to swap even
// and odd bits
unsigned int swapBits(unsigned int x)
{
unsigned int even_bits = x
Language:
Siddhartha Paul
19 Jun, 2019 2:16 PM
import java.io.*;
public class SwapEvenOdd
{
public static int swapBits(int num)
{
int evenBits = num & 0xAAAAAAAA;
int oddBits = num & 0x55555555;
evenBits >>= 1;
oddBits <<= 1;
return (evenBits | oddBits);
}
public static void main(String[] args)throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number: ");
int num=Integer.parseInt(br.readLine());
System.out.println(swapBits(num));
}
}