在Swift中在Decimal,Binary和Hexadecimal之间转换

时间:2021-03-17 17:08:31

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

我想知道的是转换代码最有效的方法(在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...

对不起,如果问题有点长......

1 个解决方案

#1


35  

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

String和Int都有构造函数,它们采用基数(基数)。结合这些,您可以实现所有转换:

// 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"

#1


35  

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

String和Int都有构造函数,它们采用基数(基数)。结合这些,您可以实现所有转换:

// 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"