如何在 Swift 中将十六进制数转换为 bin? [英] How to convert hex number to bin in Swift?
本文介绍了如何在 Swift 中将十六进制数转换为 bin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有字符串变量:var str = "239A23F"如何将此字符串转换为二进制数?str.toInt()
不起作用.
I have string variable:
var str = "239A23F"
How do I convert this string to a binary number?
str.toInt()
does not work.
推荐答案
您可以使用 Foundation 框架中的 NSScanner()
:
You can use NSScanner()
from the Foundation framework:
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) 开始, 所有整数类型都有一个
As of Swift 2 (Xcode 7), all integer types have an
public init?(_ text: String, radix: Int = default)
初始化器,以便提供纯 Swift 解决方案:
initializer, so that a pure Swift solution is available:
let str = "239A23F"
let num = Int(str, radix: 16)
这篇关于如何在 Swift 中将十六进制数转换为 bin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文