ADVERTISEMENT
ADVERTISEMENT

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 »


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.