Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert hex number to bin in Swift?

Tags:

hex

swift

binary

I have string variable: var str = "239A23F" How do I convert this string to a binary number? str.toInt() does not work.

like image 634
subdan Avatar asked Oct 09 '14 17:10

subdan


1 Answers

You can use NSScanner() from the Foundation framework:

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

Or the BSD library function strtoul()

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

As of Swift 2 (Xcode 7), all integer types have an

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

initializer, so that a pure Swift solution is available:

let str = "239A23F"
let num = Int(str, radix: 16)
like image 122
Martin R Avatar answered Oct 01 '22 21:10

Martin R