How to convert hexadecimal digit to a decimal value in Java

2 Answers

0 votes
public class MyClass {
    public static void main(String args[]) {
        String hex = "C";
        char ch = hex.charAt(0);
       
        if (ch <= 'F' && ch >= 'A') {
           int value = ch - 'A' + 10;
           System.out.println("Decimal value = " + value);
        } 
        else if (Character.isDigit(ch)) {
            System.out.println("Decimal value = " + ch);
        }
        else {
            System.out.println("Hex digit error");
        }
    }
}


/*
run:

Decimal value = 12

*/

 



answered Jun 13, 2019 by avibootz
0 votes
public class MyClass {
    static int convert_hex_to_dec(String hex) {
        char ch = hex.charAt(0);
       
        if (ch <= 'F' && ch >= 'A') {
           return ch - 'A' + 10;
        } 
        else if (Character.isDigit(ch)) {
            return ch - '0';
        }
        else {
            return -1;
        }
    }
    public static void main(String args[]) {
        System.out.println(convert_hex_to_dec("C"));
        System.out.println(convert_hex_to_dec("3"));
        System.out.println(convert_hex_to_dec("x"));
    }
}



/*
run:

12
3
-1

*/

 



answered Jun 13, 2019 by avibootz

Related questions

1 answer 171 views
1 answer 142 views
1 answer 150 views
1 answer 144 views
1 answer 172 views
...