📜  每两位交换字节

📅  最后修改于: 2021-04-27 21:21:42             🧑  作者: Mango

将所有一对位交换为一个字节。交换之前:11-10-11-01交换之后:11-01-11-10
例子:

Input  : 00000010
Output : 00000001

Input  : 00000100
Output : 00001000

方法:
x =((x&0b10101010)>> 1)| ((x&0b01010101)<> 1提取高位位置并将其移至低位位置。
类似地,表达式(x&0b01010101)<< 1从每对中提取低位并将其移到高位位置。
然后使用逐位或将这两部分组合在一起。

x= 00011010
((x & 0b10101010) >> 1) = 00001010 >> 1
                        = 00000101
((x & 0b01010101) << 1) = 00010000 <> 1) | ((x & 0b01010101) << 1) = 00100101

下面是上述的实现:
注意:此解决方案仅适用于8位。

C++
// C++ program to swap every two bits in a byte.
#include
using namespace std;
 
unsigned int swapBitsInPair(unsigned int x)
{
    // Extracting the high bit shift it to lowbit
    // Extracting the low bit shift it to highbit
    return ((x & 0b10101010) >> 1) |
            ((x & 0b01010101) << 1);   
}
 
/* Driver function to test above function */
int main()
{
    unsigned int x = 4;
    cout << swapBitsInPair(x);   
    return 0;
}


Java
// Java program to swap every
// two bits in a byte.
import java.util.*;
 
class GFG
{
    static int swapBitsInPair( int x)
    {
        // Extracting the high bit shift it to lowbit
        // Extracting the low bit shift it to highbit
        return ((x & 0b10101010) >> 1) |
                ((x & 0b01010101) << 1);
    }
 
    // Driver Function
    public static void main(String[] args)
    {
    int x = 4;
    System.out.print(swapBitsInPair(x));
    }
}
 
// This code is contributed by Gitanjali.


Python3
# Python program to swap every
# two bits in a byte.
 
import math
 
def swapBitsInPair( x):
 
    # Extracting the high bit shift it to lowbit
    # Extracting the low bit shift it to highbit
    return ((x & 0b10101010) >> 1) or ((x & 0b01010101) << 1)
 
# driver Function
x = 4;
print(swapBitsInPair(x))
 
# This code is contributed by Gitanjali.


C#
// C# program to swap every two bits in a byte.
using System;
 
public class GFG{
 
    static uint swapBitsInPair(uint x)
    {
        // Extracting the high bit shift it to lowbit
        // Extracting the low bit shift it to highbit
        return ((x & 010101010) >> 1) |
                ((x & 001010101) << 1);
    }
     
    // Driver function to test above function
    static public void Main () {
         
        uint x = 4;
         
        Console.WriteLine(swapBitsInPair(x));
    }
}
 
// This code is contributed by vt_m.


PHP
> 1) |
           (($x & 0b01010101) << 1);
}
 
    // Driver Code
    $x = 4;
    echo swapBitsInPair($x);
 
// This code is contributed by mits
?>


Javascript


输出:

8

参考:
https://stackoverflow.com/questions/4788799/swap-every-pair-of-bits-in-byte