Cobie Fisher Cobie Fisher - 7 months ago 356
Swift Question

Convert between Decimal, Binary and Hexadecimal in Swift

What I want to know is the most code efficient way to convert (in swift 2):


  • Decimal to Binary

  • Binary to Decimal

  • Decimal to Hexadecimal

  • Hexadecimal to Decimal

  • Binary to Hexadecimal

  • Hexadecimal to Binary



I already have a rudimentary and long-winded way of achieving this, but I would like to find out a very efficient way of doing it.

Sorry if the question is a bit long...

Answer
// Decimal to binary
let b = String(21, radix: 2)
print(b) // "10101"

// Binary to decimal
let d = Int(b, radix: 2)!
print(d) // 21

// Decimal to hexadecimal
let h = String(21, radix: 16)
print(h) // "15"

// Hexadecimal to decimal
let d2 = Int(h, radix: 16)!
print(d2) // 21

// Binary to hexadecimal
let b2 = "10101011"
let h2 = String(Int(b2, radix: 2)!, radix: 16)
print(h2) // "ab"

// Hexadecimal to binary
let h3 = "face"
let b3 = String(Int(h3, radix: 16)!, radix: 2)
print(b3) // "1111101011001110"
Comments