-2

What i really want to know is what is the quickest way of converting this in swift

  • Binary to Hexadecimal
  • Hexadecimal to Binary
  • Binary to Decimal
  • Decimal to Binary

These are the conversation i am trying to do in swift

Sulthan
  • 128,090
  • 22
  • 218
  • 270
MikeTheDEV
  • 11
  • 1
  • What have you tried? The algorithm is rather simple and there are actually library functions for that. Look at `String`/`Int` initializers. https://developer.apple.com/documentation/swift/string/2997127-init and https://developer.apple.com/documentation/swift/int/2924481-init – Sulthan Aug 21 '18 at 06:23
  • 1
    Take the pain and please search on google. Thanks. – jack jay Aug 21 '18 at 06:23

1 Answers1

2

Using native String and Int initializers:

extension String {
    func convertBase(from: Int, to: Int) -> String? {
        return Int(self, radix: from)
            .map { String($0, radix: to) }
    }
}

let binary = "000010001"
let decadic = binary.convertBase(from: 2, to: 10)
print(decadic)
let hexadecimal = binary.convertBase(from: 2, to: 16)
print(hexadecimal)
Sulthan
  • 128,090
  • 22
  • 218
  • 270