In Swift, how do you convert a String to Int64?

29.7k views Asked by At

I am loading in lines from a text file with very large numbers. String has the toInt method, but how do you convert a string to an Int64 which will be able to handle the large numbers?

I don't see a toInt64 method or a toLong etc. There must be a way, but I haven't found anything by searching yet.

Alternatively I guess I could read the numbers in the string digit by digit (or by groups of digits) and then add them together with appropriate factors of ten, but that seems like overkill. Or maybe the proper way is to read the data in a binary form and convert it that way?

Thanks

4

There are 4 answers

1
Laevand On BEST ANSWER

As of Swift 2.1.1 you can simply initialize Int64 with String

let number: Int64? = Int64("42")
0
newacct On
import Darwin
let str = ...
let i = strtoll(str, nil, 10)
2
Mobile Ben On

If you don't mind using NSString, you can do this:

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

Note that unlike toInt(), longLongValue will return 0 if the string is not a legal number whereas toInt() will return nil in that case.

0
Hal On
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