Languages
[Edit]
EN

Java - convert hex to int

4 points
Created by:
Lennie-S
439

Short solution:

String hex = "a";
int number = Integer.parseInt(hex, 16);

System.out.println(number); // 10

The best way to convert hex String to int in java is to use Integer.parseInt() method.

Syntax:

Integer.parseInt(String hexString, int radix)

1. Convert couple of different hex to int

public class Example1 {

    public static void main(String[] args) {

        System.out.println( Integer.parseInt("5", 16) );  // 5
        System.out.println( Integer.parseInt("a", 16) );  // 10
        System.out.println( Integer.parseInt("b", 16) );  // 11
        System.out.println( Integer.parseInt("f", 16) );  // 15
        System.out.println( Integer.parseInt("10", 16) ); // 16
        System.out.println( Integer.parseInt("1f", 16) ); // 31
        System.out.println( Integer.parseInt("20", 16) ); // 32
        System.out.println( Integer.parseInt("21", 16) ); // 33
    }
}

Output:

5
10
11
15
16
31
32
33

2. Convert hex to int in loop - from 0 to 20

public class Example2 {

    public static void main(String[] args) {

        System.out.println("Hex | Dec");

        for (int number = 0; number <= 16; number++) {

            String hex = Integer.toHexString(number);
            int backToDecimal = Integer.parseInt(hex, 16);

            System.out.println(String.format("%3s", hex) + " - "
                    + String.format("%3s", backToDecimal));
        }
    }
}

Output:

Hex | Dec
  0 -   0
  1 -   1
  2 -   2
  3 -   3
  4 -   4
  5 -   5
  6 -   6
  7 -   7
  8 -   8
  9 -   9
  a -  10
  b -  11
  c -  12
  d -  13
  e -  14
  f -  15
 10 -  16

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java conversion

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join