Java program to swap two nibbles in a byte

In this tutorial, we will learn to swap two nibbles in a byte and also write its code in Java.

A byte is a combination of 8 bits and one nibble consists of 4-bits. Hence every byte has two nibbles.

For example, The number 150 can be represented as 10010110 in binary. 1001 is the upper nibble whereas 0110 is the lower nibble

after swapping both the nibbles we get 01101001 which is 105 in decimal.

Let’s see how we can swap the two nibbles of a byte:

  1. Perform bitwise AND operation with hexadecimal 0F to separate the lower nibble from the byte
  2. Perform bitwise AND operation with hexadecimal F0 to separate the upper nibble from the byte
  3. Take the right nibble and left shift << by 4 positions
  4. Take the left nibble and right shift >> by 4 positions
  5. Finally, combine the nibble using the bitwise OR operator

Java program to swap two nibbles in a byte

We can combine all these five steps in a single line i.e. (num & 0x0F) << 4 | (num & 0xF0) >> 4 
where (num & 0F) <<4 separates the lower nibble and left shift by 4 positions and (num & 0xF0) >> 4 separates the upper nibble and right shift by 4 positions and finally we OR both of them to get the desired result

Java program to swap two nibbles of byte

Following is the code implementation in Java.

public class SwapNibble 
{

  public static void main(String[] args) 
  {
    int num = 150;
    int swapnum;
    
    swapnum = ((num & 0x0F) << 4 | (num & 0xF0) >> 4);
    
    System.out.println("Before swapping the nibble "+ num);
    System.out.println("After swapping the nibble "+ swapnum);

  }

}

The output of the following program is

Before swapping the nibble 150
After swapping the nibble 105

Leave a Reply

Your email address will not be published. Required fields are marked *