0

I need to make a program that can convert hexadecimal values to decimal. I got the program to work but I need to make my program display the same output no matter if the hexadecimal value entered contains the "0x" in front or not.

this is my code.

import java.util.Scanner;

public class Main {

    public static long hex2decimal(String s){
        String digits = "0123456789ABCDEF";
        int val = 0;
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            int d = digits.indexOf(c);
            val = 16*val + d;
        }
        return val;
    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        long decimal;

        System.out.println("Please enter the hex string:");
        String s = sc.next().toUpperCase();
        decimal = hex2decimal(s);
        System.out.println(decimal);

    }
}
Sam
  • 1,542
  • 2
  • 13
  • 27

1 Answers1

1

Why should you not using Integer.parseInt("121",16), rather custom logic for converting hex to decimal. Here 16 is radix telling number is hexadecimal and will be converted to decimal.

System.out.println(Integer.parseInt("121",16));
Gaurav Srivastav
  • 2,381
  • 1
  • 15
  • 18