📜  在一个字节中交换两个半字节

📅  最后修改于: 2021-05-25 08:32:36             🧑  作者: Mango

半字节是四位聚合或半个八位位组。一个字节中有两个半字节。
给定一个字节,交换其中的两个半字节。例如,100以一个字节(或8位)表示为01100100。这两个半字节是(0110)和(0100)。如果交换两个半字节,则会得到01000110(十进制为70)。

要交换半字节,我们可以使用按位&,按位”运算符。可以使用C中的无符号char表示一个字节,因为在典型的C编译器中char的大小为1个字节。
以下是上述想法的实现。

C++
// C++ program to swap two
// nibbles in a byte
#include 
using namespace std;
 
int swapNibbles(int x)
{
    return ( (x & 0x0F) << 4 | (x & 0xF0) >> 4 );
}
 
// Driver code
int main()
{
    int x = 100;
    cout << swapNibbles(x);
    return 0;
}
 
//This code is contributed by Shivi_Aggarwal


C
#include 
 
unsigned char swapNibbles(unsigned char x)
{
    return ( (x & 0x0F)<<4 | (x & 0xF0)>>4 );
}
 
int main()
{
    unsigned char x = 100;
    printf("%u", swapNibbles(x));
    return 0;
}


Java
// Java program to swap two
// nibbles in a byte
 
class GFG {
     
static int swapNibbles(int x)
{
    return ((x & 0x0F) << 4 | (x & 0xF0) >> 4);
}
 
// Driver code
public static void main(String arg[])
{
    int x = 100;
    System.out.print(swapNibbles(x));
}
}
 
// This code is contributed by Anant Agarwal.


Python3
# python program Swap
# two nibbles in a byte
 
def swapNibbles(x):
    return ( (x & 0x0F)<<4 | (x & 0xF0)>>4 )
 
# Driver code
 
x = 100
print(swapNibbles(x))
 
# This code is contributed
# by Anant Agarwal.


C#
// C# program to swap two
// nibbles in a byte
using System;
 
class GFG {
 
// Function for swapping   
static int swapNibbles(int x)
{
    return ((x & 0x0F) << 4 |
            (x & 0xF0) >> 4);
}
 
// Driver code
public static void Main()
{
    int x = 100;
    Console.Write(swapNibbles(x));
}
}
 
// This code is contributed by Nitin Mittal.


PHP
> 4 );
}
 
    // Driver Code
    $x = 100;
    echo swapNibbles($x);
 
// This Code is Contributed by Ajit
?>


Javascript


输出:

70