3

I need to convert the string of hex to decimal in java..

My hex value is "00000156A56BE980".

My required output is 1471654128000

I have done the following in java,

public static void main (String args [])
{
  String hexValue = " 00000156A56BE980 ";
  Integer result = Integer.parseInt(hexValue, 16);
 System.out.println(result);
}

but I am getting the following error,

Number format Exception for input string "00000156A56BE980"

I have tried by giving long also the same error coming.. For other hex value it's coming but when we give hex string of larger value it shows the error.

How can we convert this number to decimal? Can anyone solve this issue for me?

jschreiner
  • 4,840
  • 2
  • 12
  • 16
Anand
  • 79
  • 3
  • 8
  • Yeah I have tried tat also.. The same error throwing.. – Anand Aug 20 '16 at 11:01
  • You get a `NumberFormatException` because there's a space at the end of the string you're trying to parse. Get rid of the space. Also, if the value is too large to fit into an `int` you'll get this exception. – Jesper Aug 20 '16 at 11:05

4 Answers4

5

Try it like so

import java.math.*;

class Main {
    public static void main (String args [])
    {
        String hexValue = "00000156A56BE980";
        BigInteger result = new BigInteger(hexValue, 16);
        System.out.println(result);
    }
}

See also this repl.it

The problem is probably because your value does not fit within the value range (-231 to 232-1) of Integer - see the docs

DAXaholic
  • 33,312
  • 6
  • 76
  • 74
1

The number is too large for a 32-bit int

Try using a long instead.

public static void main(String[] args) {
    String hexValue = "00000156A56BE980";
    long result = Long.parseLong(hexValue, 16);
    System.out.println(result);
}

Note: you can't have spaces in a number. You can call .trim() to remove them.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

2 thing in order the code can work:

  1. remove spaces trimming the String
  2. the result doenst fit in an integer so use either Long or BigInteger instead

 public static void main(String[] args) {
    String hexValue = " 00000156A56BE980 ";
    long result = Long.parseLong(hexValue.trim(), 16);
    System.out.println(result);
    }
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

The number is too big for integer (> 2^32).

(The value represented by the string is not a value of type int.)

Take a look here

Community
  • 1
  • 1
PKey
  • 3,715
  • 1
  • 14
  • 39