Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Using loops write a program that converts a hexadecimal integer number to its decimal form.
- * The input is entered as string. The output should be a variable of type long. */
- import java.util.Scanner;
- public class _15_HexadecimalToDecimalNumber {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner scan = new Scanner(System.in);
- System.out.print("Enter your Hexadecimal number on the line: ");
- String hexadecStr = scan.next();
- scan.close();
- if (hexadecStr.indexOf("0x") <= 0) {
- if (hexadecStr.indexOf("0x") == 0) {
- hexadecStr = hexadecStr.substring(2);
- }
- hexadecStr = hexadecStr.toUpperCase();
- // Short variant:
- // long decNum = Long.parseLong(hexadecStr, 16);
- long decNum = 0;
- long multiplier = 1;
- for (int i = hexadecStr.length() - 1; i >= 0; i--) {
- char hexDigit = hexadecStr.charAt(i);
- int tempNum = convertHexadecimalCharToDecimalNumber(hexDigit);
- decNum += tempNum * multiplier;
- multiplier *= 16;
- }
- System.out.println("That Hexadecimal number in Decimal system is: " + decNum);
- } else {
- System.out.println("Error! - Invalid Input number!!!");
- }
- }
- private static int convertHexadecimalCharToDecimalNumber(char digit) {
- // TODO Auto-generated method stub
- switch (digit) {
- case 'A':
- return 10;
- case 'B':
- return 11;
- case 'C':
- return 12;
- case 'D':
- return 13;
- case 'E':
- return 14;
- case 'F':
- return 15;
- default:
- return Integer.parseInt("" + digit);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement