Q:

Java program to swap two nibbles of a given byte

belongs to collection: Java Basic Programs

0

Java program to swap two nibbles of a given byte

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to swap two nibbles of a given byte is given below. The given program is compiled and executed successfully.

// Java program swap two nibbles 
// of a given byte

import java.util.Scanner;

public class Main {
  static byte swapTwoNibbles(byte val) {
    byte num;
    num = (byte)((val & 0x0F) << 4 | (val & 0xF0) >> 4);
    return num;
  }

  public static void main(String[] args) {
    Scanner SC = new Scanner(System.in);

    byte num = 0;
    byte res = 0;

    System.out.printf("Enter number: ");
    num = SC.nextByte();

    res = swapTwoNibbles(num);

    System.out.printf("\nNumber after swapping nibbles : %d\n", res);
  }
}

Output:

Enter number: 64

Number after swapping nibbles : 4

Explanation:

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contains two static methods swapTwoNibbles() and main().

The swapTwoNibbles() method is used to swap two nibbles of a given byte using bitwise operators and return the result to the calling method.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to demonstrate the example of left sh... >>
<< Java program to reverse bits of the given number...