简体   繁体   中英

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

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

从Swift 2.1.1开始,您只需使用String初始化Int64即可

let number: Int64? = Int64("42")

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.

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

import Darwin
let str = ...
let i = strtoll(str, nil, 10)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM