11

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

Galik
  • 47,303
  • 4
  • 80
  • 117
Daniil Subbotin
  • 6,138
  • 5
  • 20
  • 24

1 Answers1

25

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)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Appreciate the answer. Maybe I am missing something, but how is "37331519" binary? – iOS Blacksmith Sep 06 '22 at 09:11
  • @iOSBlacksmith: Here “binary number” again means an integer (with binary representation in memory). Note that `Int` conforms to the `BinaryInteger` protocol. – The terms “integer”, “decimal”, “binary number” etc are not always used coherently. – This applies to your last remark here https://stackoverflow.com/questions/26790660/how-to-convert-a-binary-to-decimal-in-swift/26810937?noredirect=1#comment130003632_26810937 as well. – Martin R Sep 06 '22 at 09:19