Search code examples
javascriptjavaparseint

Java parse hexadecimal as a integer


When i paste parseInt("3cf1bb13f1c96", 16) to javascript console, it successfuly converts to integer value which is 1072142774901910 but when i use Integer.parseInt("3cf1bb13f1c96", 16) in java it prints something

Exception in thread "main" java.lang.NumberFormatException: For input string: "3cf1bb13f1c96"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at Main.example(Main.java:line)
    at Main.example(Main.java:line)

Solution

  • The value you are parsing is out of Integer range. In Java, the integer ranges from -2,147,483,648 to +2,147,483,647 . Try to use Long instead:

     Long.parseLong("3cf1bb13f1c96", 16) 
    

    it parses successfully:

    > Task :Foo.main()
    1072142774901910