ADVERTISEMENT
ADVERTISEMENT

Java program to swap two nibbles of a given byte

Given/input a byte value, we have to swap its two nibbles.
Submitted by Nidhi, on March 07, 2022

Problem Solution:

In this program, we will read a byte from the user and swap nibbles of the given byte.

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.

The main() method is an entry point for the program. Here, we read a byte from the user using the Scanner class. Then we called the swapTwoNibbles() method to swap nibbles of the byte. After that, we printed the result.

Java Basic Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.