Java Program to Convert Number From Decimal to Hexadecimal

Java Program to Convert Number From Decimal to Hexadecimal

Java Program to Convert Number From Decimal to Hexadecimal

// 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));
  }
}
// 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);
  }
}
Complie 	:	javac CovDec2Hex.java
Run		:	java CovDec2Hex
Output
Enter any integer number: 31231
79FF
Complie 	:	javac CovDec2Hex.java
Run		:	java CovDec2Hex
Output
Enter any integer number: 31231
Hexadecimal Number is: 79ff

Hi, I'm Selva a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment