0

I am trying to convert an hexadecimal number into a decimal number, but it doesn't work for very large values (over 2,147,483,647 in decimal),because int type is limited there.

Here is my code which works for integers

String nombreHexa = h2d.getText().toString();
            if (isHex(nombreHexa) == true) {
                int deciInt = Integer.parseInt(nombreHexa, 16);
                String newDeci = String.valueOf(deciInt);
                resulth2d.setText(newDeci);
            }

I tried to make deciInt a long but it wasn't so simple. The problem seems to come from the parseInt function (parseLong doesn't exist as well)

Does some one know how I should do it?

WhiskThimble
  • 547
  • 3
  • 10
  • 23

3 Answers3

1

As this answer suggest, use Long.decode(str):

Decodes a String into a Long. Accepts decimal, hexadecimal, and octal numbers.

If you need larger than Long.MAX_VALUE, you should probably use BigInteger.

Community
  • 1
  • 1
Adam Matan
  • 128,757
  • 147
  • 397
  • 562
  • I tried walenborn's code and it works, but this way works too, and it allows BigInteger (which I didn't know) Thanks! – WhiskThimble Mar 12 '13 at 11:16
1

Whta's wrong with Long.parseLong(String num, int radix)?

String nombreHexa = h2d.getText().toString();
        if (isHex(nombreHexa) == true) {
            long deciLong = Long.parseLong(nombreHexa, 16);
            String newDeci = String.valueOf(deciLong);
            resulth2d.setText(newDeci);
        }
wallenborn
  • 4,158
  • 23
  • 39
  • I don't know what was the problem when I tried it, maybe I forgot something. But with your code, it works. Thanks! Edit : My bad, I just figured out what was wrong : I used Long.Long(nombreHexa, 16); (without the parse) – WhiskThimble Mar 12 '13 at 11:11
0

parseLong exists as well. As long as it is only a size problem, you can use it.

uba
  • 2,012
  • 18
  • 21