web-dev-qa-db-fra.com

Convertir entre décimal, binaire et hexadécimal en Swift

Ce que je veux savoir, c'est le moyen le plus efficace de convertir (en Swift 2):

  • Décimal en binaire
  • Binaire en décimal
  • Décimal en hexadécimal
  • Hexadécimal en décimal
  • Binaire à hexadécimal
  • Hexadécimal en binaire

J'ai déjà un moyen rudimentaire et de longue haleine d'y parvenir, mais je voudrais trouver un moyen très efficace de le faire.

Désolé si la question est un peu longue ...

19
Cobie Fisher

String et Int ont des initialiseurs qui prennent un radix (base). En les combinant, vous pouvez réaliser toutes les 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"
48
vacawama