21

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

shim
  • 9,289
  • 12
  • 69
  • 108
  • 2
    If you compile as a 64-bit app then `Int` *is* a 64-bit integer. – Martin R Nov 29 '14 at 06:04
  • 1
    While the answers below are perfectly valid, in my case @MartinR 's answer was the most helpful. If you add it as an answer I can give you the answer credit. – shim Apr 08 '15 at 06:50

4 Answers4

42

As of Swift 2.1.1 you can simply initialize Int64 with String

let number: Int64? = Int64("42")
Laevand
  • 822
  • 9
  • 14
10

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.

shim
  • 9,289
  • 12
  • 69
  • 108
Mobile Ben
  • 7,121
  • 1
  • 27
  • 43
  • I'm trying to do this same thing but get an unsigned Int64. I tried looking through NSString but unfortunately theres no methods that return an UInt64. I was wondering if you had any ideas? Maybe it should be a new question? – Lightbulb1 Mar 11 '15 at 12:43
  • @Lightbulb1 you can use the C function `strtoull`. Example: `strtoull(str, nil, 10)`. The first parameter is the string and the third parameter is the base to convert from. I don't know what the second parameter dose. – Gustaf Rosenblad Jan 08 '16 at 23:57
4
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

Hal
  • 141
  • 1
  • 3
1
import Darwin
let str = ...
let i = strtoll(str, nil, 10)
newacct
  • 119,665
  • 29
  • 163
  • 224