In Swift, how do you convert String to Int64?

I am loading lines from a text file with very large numbers. String has a toInt method, but how to convert a string to Int64 that can handle large numbers?

I do not see the method toInt64 or toLong, etc. There should be a way, but I haven't found anything yet by doing a search.

As an alternative, I assume that I could read the digits in a string digit by a digit (or groups of digits), and then add them along with the corresponding coefficients of ten, but this seems superfluous. Or maybe the right way is to read the data in binary form and convert it that way?

thanks

+7
string long-integer xcode swift int64
source share
5 answers

(From my comment above :) If you are compiling as a 64-bit application, then Int is a 64-bit integer.

0
source share

With Swift 2.1.1, you can simply initialize Int64 with String

 let number: Int64? = Int64("42") 
+15
source share

If you don't mind using NSString, you can do it

 let str = "\(LLONG_MAX)" let strAsNSString = str as NSString let value = strAsNSString.longLongValue 

Note that unlike toInt () longLongValue returns 0 if the string is not a legal number, while toInt () will return zero in this case.

+10
source share
 import Darwin let str = ... let i = strtoll(str, nil, 10) 
+1
source share
 import Darwin let strBase10 = "9223372036854775807" let i64FromBase10 = strtoll(strBase10, nil, 10) let strBase16 = "0xFFFFFFFFFFFFFFFF" let i64FromBase16 = strtoll(strBase16, nil, 16) 

strtoll means STRINGTOLongLong

http://www.freebsd.org/cgi/man.cgi?query=strtoll

+1
source share

All Articles