我想知道的是最有效的代码转换方式(迅速2):
我已经有了实现该目标的基本且漫长的方法,但是我想找到一种非常有效的方法。
抱歉,问题有点长…
两者String和Int都有带有radix(基)的初始化程序。结合这些,您可以实现所有转化:
String
Int
radix
// 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"