Swap every two bits in bytes
Swap all the pair of bits in a byte. Before swapping: 11-10-11-01 After swapping: 11-01-11-10
Examples:
Input : 00000010
Output : 00000001
Input : 00000100
Output : 00001000
Approach:
x = ((x & 0x55555555) >> 1) | ((x & 0xAAAAAAAA) <> 1 extracts the high bit position and shifts it to the low bit position.
Similarly the expression (x & 0xAAAAAAAA) << 1 extracts the low bit from each pair and shifts it to the high bit position.
The two parts are then combined using bitwise-OR.
x= 00011010
((x & 0xAAAAAAAA) >> 1) = 00001010 >> 1
= 00000101
((x & 0x55555555) << 1) = 00010000 <> 1) | ((x & 0x55555555) << 1) = 00100101
Below is the implementation of the above idea:
C++
#include<bits/stdc++.h>
using namespace std;
unsigned int swapBitsInPair(unsigned int x)
{
return ((x & 0xAAAAAAAA) >> 1) |
((x & 0x55555555) << 1);
}
int main()
{
unsigned int x = 4;
cout << swapBitsInPair(x);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int swapBitsInPair( int x)
{
return ((x & 0xAAAAAAAA ) >> 1 ) |
((x & 0x55555555 ) << 1 );
}
public static void main(String[] args)
{
int x = 4 ;
System.out.print(swapBitsInPair(x));
}
}
|
Python3
import math
def swapBitsInPair( x):
return ((x & 0xAAAAAAAA ) >> 1 ) or ((x & 0x55555555 ) << 1 )
x = 4 ;
print (swapBitsInPair(x))
|
C#
using System;
public class GFG{
static uint swapBitsInPair( uint x)
{
return ((x & 0xAAAAAAAA) >> 1) |
((x & 0x55555555) << 1);
}
static public void Main () {
uint x = 4;
Console.WriteLine(swapBitsInPair(x));
}
}
|
PHP
<?php
function swapBitsInPair( $x )
{
return (( $x & 0xAAAAAAAA) >> 1) |
(( $x & 0x55555555) << 1);
}
$x = 4;
echo swapBitsInPair( $x );
?>
|
Javascript
<script>
function swapBitsInPair(x)
{
return ((x & 0xAAAAAAAA) >> 1) |
((x & 0x55555555) << 1);
}
let x = 4;
document.write( swapBitsInPair(x));
</script>
|
Output:
8
Time Complexity: O(1)
Space Complexity: O(1)
Reference:
https://stackoverflow.com/questions/4788799/swap-every-pair-of-bits-in-byte
Last Updated :
22 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...