0

0x1 is the hexadecimal form of 1. More information is in this link.
I'm trying to convert that 0x1 into 1. So I'm using this code.

    String hex = "0x1";
    int decimal = Integer.parseInt(hex, 16);
    System.out.println(decimal);

However, it returns exception as

Exception in thread "main" java.lang.NumberFormatException: For input string: "0x1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at HelloWorld.main(HelloWorld.java:7)

How can I make this java code print 1?

Ajay Kulkarni
  • 2,900
  • 13
  • 48
  • 97

1 Answers1

2

You can use Integer.decode:

String hex = "0x1";
int value = Integer.decode(hex);
System.out.println(value);

(Note: I've renamed the integer variable from 'decimal' to 'value', since there's nothing specifically decimal about it; it's just an integer. It's actually represented as binary internally.)

ruakh
  • 175,680
  • 26
  • 273
  • 307