×

Java Programs

Java Practice

Java program to convert hexadecimal byte to decimal

Given a byte value in the hexadecimal format, we have to convert hexadecimal byte to decimal.
Submitted by Nidhi, on March 02, 2022

Problem statement

In this program, we will convert the hexadecimal byte into a decimal number and print the result.

Java program to convert hexadecimal byte to decimal

The source code to convert hexadecimal byte to decimal is given below. The given program is compiled and executed successfully.

// Java program to convert hexadecimal Byte 
// to an integer

public class Main {
  static int getNum(char ch) {
    int num = 0;

    if (ch >= '0' && ch <= '9') {
      num = ch - 0x30;
    } else {
      switch (ch) {
      case 'A':
      case 'a':
        num = 10;
        break;

      case 'B':
      case 'b':
        num = 11;
        break;

      case 'C':
      case 'c':
        num = 12;
        break;

      case 'D':
      case 'd':
        num = 13;
        break;

      case 'E':
      case 'e':
        num = 14;
        break;

      case 'F':
      case 'f':
        num = 15;
        break;

      default:
        num = 0;
      }
    }
    return num;
  }

  static int hex2int(String hex) {
    int x = 0;

    x = (getNum(hex.charAt(0))) * 16 + (getNum(hex.charAt(1)));

    return x;
  }

  public static void main(String[] args) {
    String hexValue = "7F";
    int intValue = 0;

    intValue = hex2int(hexValue);

    System.out.printf("Value is: %d\n", intValue);
  }
}

Output

Value is: 127

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 three static methods getNum(), hex2int(), and main().

The getNum() method is used to get a decimal digit from a hexadecimal digit and return the result to the calling method.

The hex2int() method is used to return a decimal number from the hexadecimal number and return the result to the calling method.

The main() method is an entry point for the program. Here, we created a string variable hexValue initialized with "7F". Then we converted the hex value into decimal using the hex2int() method and printed the result.

Java Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.