gpt4 book ai didi

swift - 如何在 Swift 中将十六进制数转换为 bin?

转载 作者:IT王子 更新时间:2023-10-29 05:33:49 25 4
gpt4 key购买 nike

我有字符串变量:var str = "239A23F"如何将此字符串转换为二进制数?str.toInt() 不起作用。

最佳答案

您可以使用 Foundation 框架中的 NSScanner():

let scanner = NSScanner(string: str)
var result : UInt32 = 0
if scanner.scanHexInt(&result) {
println(result) // 37331519
}

或者BSD库函数strtoul()

let num = strtoul(str, nil, 16)
println(num) // 37331519

Swift 2 (Xcode 7) 开始,所有整数类型都有一个

public init?(_ text: String, radix: Int = default)

初始化器,以便提供纯 Swift 解决方案:

let str = "239A23F"
let num = Int(str, radix: 16)

关于swift - 如何在 Swift 中将十六进制数转换为 bin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26284223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com