views:

265

answers:

3

I've really a long sequence of characters such as 123222222222230000000000001. I want to convert this to a long. What is the most efficient way to do it in Java?

UPDATE: The max length of sequence is of 31 characters

+1  A: 

You cannot fit 31 digits into a long, but just for reference:

 long primitive = Long.parseLong(longString); 
 Long object = Long.valueOf(longString);
Thilo
the first line throws an error. so I'm pretty much sure this doesn't work
newbie
what kind of error?
Thilo
java.lang.NumberFormatException
newbie
that is because your number is "too long". You need to use a BigInteger.
Thilo
+9  A: 

First of all, a string value like that will never fit into a long (it is much to large),

You will need to use the BigInteger type and the constructor that accepts a String parameter:

Translates the decimal String representation of a BigInteger into a BigInteger. The String representation consists of an optional minus sign followed by a sequence of one or more decimal digits. The character-to-digit mapping is provided by Character.digit. The String may not contain any extraneous characters (whitespace, for example).

Andrew Hare
true. The example string is "too long".
Thilo
sorry for making it too long than required, the max length will be of 31 characters that I need to convert
newbie
Given the fact Long.MAX_VALUE = 2^63 - 1, which has 19 digits in it, there's still no chance it'll fit in a long. Use BigInteger as suggested.
Juliet
+1  A: 
valli
but not the 31-digit strings he has in mind. Those are just too long for long.
Thilo