Convert between Decimal, Binary and Hexadecimal in Swift

前端 未结 2 2050
旧时难觅i
旧时难觅i 2020-12-04 22:26

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
  • <
2条回答
  •  我在风中等你
    2020-12-04 22:42

    Both String and Int have initializers which take a radix (base). Combining those, you can achieve all of the conversions:

    // Decimal to binary
    let d1 = 21
    let b1 = String(d1, radix: 2)
    print(b1) // "10101"
    
    // Binary to decimal
    let b2 = "10110"
    let d2 = Int(b2, radix: 2)!
    print(d2) // 22
    
    // Decimal to hexadecimal
    let d3 = 61
    let h1 = String(d3, radix: 16)
    print(h1) // "3d"
    
    // Hexadecimal to decimal
    let h2 = "a3"
    let d4 = Int(h2, radix: 16)!
    print(d4) // 163
    
    // Binary to hexadecimal
    let b3 = "10101011"
    let h3 = String(Int(b3, radix: 2)!, radix: 16)
    print(h3) // "ab"
    
    // Hexadecimal to binary
    let h4 = "face"
    let b4 = String(Int(h4, radix: 16)!, radix: 2)
    print(b4) // "1111101011001110"
    

提交回复
热议问题