Advertisement
dimipan80

Hexadecimal to Decimal Number

Aug 8th, 2014
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.54 KB | None | 0 0
  1. /* Using loops write a program that converts a hexadecimal integer number to its decimal form.
  2.  * The input is entered as string. The output should be a variable of type long. */
  3.  
  4. import java.util.Scanner;
  5.  
  6. public class _15_HexadecimalToDecimalNumber {
  7.  
  8.     public static void main(String[] args) {
  9.         // TODO Auto-generated method stub
  10.         Scanner scan = new Scanner(System.in);
  11.         System.out.print("Enter your Hexadecimal number on the line: ");
  12.         String hexadecStr = scan.next();
  13.         scan.close();
  14.  
  15.         if (hexadecStr.indexOf("0x") <= 0) {
  16.             if (hexadecStr.indexOf("0x") == 0) {
  17.                 hexadecStr = hexadecStr.substring(2);
  18.             }
  19.  
  20.             hexadecStr = hexadecStr.toUpperCase();
  21.  
  22.             // Short variant:
  23.             // long decNum = Long.parseLong(hexadecStr, 16);
  24.  
  25.             long decNum = 0;
  26.             long multiplier = 1;
  27.             for (int i = hexadecStr.length() - 1; i >= 0; i--) {
  28.                 char hexDigit = hexadecStr.charAt(i);
  29.                 int tempNum = convertHexadecimalCharToDecimalNumber(hexDigit);
  30.                 decNum += tempNum * multiplier;
  31.                 multiplier *= 16;
  32.             }
  33.  
  34.             System.out.println("That Hexadecimal number in Decimal system is: " + decNum);
  35.         } else {
  36.             System.out.println("Error! - Invalid Input number!!!");
  37.         }
  38.     }
  39.  
  40.     private static int convertHexadecimalCharToDecimalNumber(char digit) {
  41.         // TODO Auto-generated method stub
  42.         switch (digit) {
  43.         case 'A':
  44.             return 10;
  45.         case 'B':
  46.             return 11;
  47.         case 'C':
  48.             return 12;
  49.         case 'D':
  50.             return 13;
  51.         case 'E':
  52.             return 14;
  53.         case 'F':
  54.             return 15;
  55.  
  56.         default:
  57.             return Integer.parseInt("" + digit);
  58.         }
  59.     }
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement