Skip to content

Instantly share code, notes, and snippets.

@anujku
Created December 14, 2014 21:04
Show Gist options
  • Save anujku/fd16e7f853226010b8a8 to your computer and use it in GitHub Desktop.
Save anujku/fd16e7f853226010b8a8 to your computer and use it in GitHub Desktop.
String to long converter
/**
* The Class StringLongConverter.
*/
public class StringLongConverter {
/**
* This method converts a String to long value.
*
* @param stringToBeConverted the string to be converted
* @return the long value
*/
public long stringToLong(String stringToBeConverted) {
int length = stringToBeConverted.length();
boolean isNeg = stringToBeConverted.charAt(0) == '-';
long longValue = 0;
int startIndex = isNeg ? 1 : 0;
char zero = '0';
int zeroAsciiVal = (int) zero;
while (length > startIndex) {
longValue *= 10;
int charVal =
stringToBeConverted.charAt(startIndex) - zeroAsciiVal;
if (charVal < 0 | charVal > 9)
throw new NumberFormatException();
longValue += charVal;
startIndex++;
}
return isNeg ? -longValue : longValue;
}
/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {
long i = new StringLongConverter().stringToLong("123");
if (i == 123)
System.out.println("Success ! " + i);
else
System.out.println("Failure");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment