Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently convert a long string to long in Java

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

like image 587
newbie Avatar asked Feb 26 '26 21:02

newbie


2 Answers

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).

like image 60
Andrew Hare Avatar answered Feb 28 '26 09:02

Andrew Hare


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

 long primitive = Long.parseLong(longString); 
 Long object = Long.valueOf(longString);
like image 41
Thilo Avatar answered Feb 28 '26 09:02

Thilo