Java program to convert number from Decimal to Hexadecimal

This program will convert integer (Decimal) number to its equivalent Hexadecimal Number.
There are two programs:
1) Without using any predefine method and
2) Using Integer.toHexString() method.

Without using any predefine method

// java program to convert decimal to hexadecimal

import java.util.*;

public class CovDec2Hex {
  public static void main(String args[]) {
    int num, counter = 0;
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter any integer number: ");
    num = sc.nextInt();

    /*to store maximum 32 digits of a number*/
    String hexVal = "";
    int dig; // to store digits
    while (num > 0) {
      dig = num % 16;
      switch (dig) {
      case 15:
        hexVal += "F";
        break;
      case 14:
        hexVal += "E";
        break;
      case 13:
        hexVal += "D";
        break;
      case 12:
        hexVal += "C";
        break;
      case 11:
        hexVal += "B";
        break;
      case 10:
        hexVal += "A";
        break;
      default:
        hexVal += Integer.toString(dig);
      }
      num = num / 16;
    }

    for (counter = hexVal.length() - 1; counter >= 0; counter--)
      System.out.print(hexVal.charAt(counter));
  }
}

Output:

Complie 	:	javac CovDec2Hex.java
Run		:	java CovDec2Hex
Output
Enter any integer number: 31231
79FF

Using Integer.toHexString() method

// java program to convert decimal to hexadecimal

import java.util.*;

public class CovDec2Hex {
  public static void main(String args[]) {
    int num;
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter any integer number: ");
    num = sc.nextInt();

    String hexVal = "";
    hexVal = Integer.toHexString(num);
    System.out.println("Hexadecimal Number is: " + hexVal);
  }
}

Output:

Complie 	:	javac CovDec2Hex.java
Run		:	java CovDec2Hex
Output
Enter any integer number: 31231
Hexadecimal Number is: 79ff

Java Number System Conversion Programs »





Comments and Discussions!

Load comments ↻





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