Dealing with Octal numbers in swift

只谈情不闲聊 提交于 2019-12-11 07:18:37

问题


I can easily turn a decimal number into an octal but I'm trying to do the reverse and I've got stuck.

let decimal = 11_224_393
let octString = String(rawAddress, radix: 8, uppercase: false)
let octal = octString.toInt()

Question

I want a function that given an Int of octal digits will read it in as an octal and convert it to decimal

such as:

// oct2dec(777) = 511
// oct2dec(10) = 8

func oct2dec(octal : Int) -> Int {
    // what goes here?
}

回答1:


Using string conversion functions is pretty horrible in my option. How about something like this instead:

func octalToDecimal(var octal: Int) -> Int {
    var decimal = 0, i = 0
    while octal != 0 {
        var remainder = octal % 10
        octal /= 10
        decimal += remainder * Int(pow(8, Double(i++)))
    }
    return decimal
}

var decimal = octalToDecimal(777) // decimal is 511



回答2:


Just use Swift native octal literals and initializers (String from integer | Int from String).

let octalInt = 0o1234 // 668
let octalString = "1234" // "1234"

let decimalIntFromOctalString = Int(octalString, radix: 0o10) // 668
let octalStringFromInt = String(octalInt, radix: 0o10) // "1234"

For your specific use-case:

let decimal = 11_224_393
let octString = String(rawAddress, radix: 0o10, uppercase: false)
guard let octal = Int(octString, radix: 0o10) else {
    print("octString was not a valid octal string:", octString)
}


来源:https://stackoverflow.com/questions/28745242/dealing-with-octal-numbers-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!