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);

    }
}
2
  • 1
    Possible duplicate of Remove part of string Commented Jun 11, 2018 at 2:50
  • 1
    if (s.startsWith("0x")) { s = s.substring(2); } Commented Jun 11, 2018 at 2:52

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

3 Comments

Integer.parseInt() does not ignore 0x, which I believe is what the asker is trying to do.
You can simply replace or ignore that before passing to parseInt
Yes, but that is what the asker is trying to achieve — not the conversion part. I suggest adding it to your code.