Search code examples
iosmacosswiftnumbershex

Is there a swift native function to convert a number to a hex string?


Is there any native Swift way for any (at least integer) number to get its hexadecimal representation in a string? And the inverse. It must not use Foundation. For example the String class has a function

func toInt() -> Int?

which converts a string representing an integer to its Int value. I am looking for something similar, using the hex strings. I know this is easily implementable, but if Swift has it there already it would be better. Otherwise if you made already an extension of String and Int to achieve the following:

let anHex = "0xA0"
if let anInt = anHex.toInt() {
   println(anInt)               // prints 128
   println(anInt.toHexString()) // prints "0xA0"
}

I know it isn't rocket science but in case please share it.

PS: This is similar to this question, the difference is that it was very related to the Foundation framework, while I am not using it in my code (nor I am importing anything else) and for now I'd like to keep it in this way, also for learning purposes.


Solution

  • As of Swift 2, all integer types have a constructor

    init?(_ text: String, radix: Int = default)
    

    so that both integer to hex string and hex string to integer conversions can be done with built-in methods. Example:

    let num = 1000
    let str = String(num, radix: 16)
    print(str) // "3e8"
    
    if let num2 = Int(str, radix: 16) {
        print(num2) // 1000
    }
    

    (Old answer for Swift 1:) The conversion from an integer to a hex string can be done with

    let hex = String(num, radix: 16)
    

    (see for example How to convert a decimal number to binary in Swift?). This does not require the import of any Framework and works with any base between 2 and 36.

    The conversion from a hex string to an integer can be done with the BSD library function strtoul() (compare How to convert a binary to decimal in Swift?) if you are willing to import Darwin.

    Otherwise there is (as far as I know) no built-in Swift method. Here is an extension that converts a string to a number according to a given base:

    extension UInt {
        init?(_ string: String, radix: UInt) {
            let digits = "0123456789abcdefghijklmnopqrstuvwxyz"
            var result = UInt(0)
            for digit in string.lowercaseString {
                if let range = digits.rangeOfString(String(digit)) {
                    let val = UInt(distance(digits.startIndex, range.startIndex))
                    if val >= radix {
                        return nil
                    }
                    result = result * radix + val
                } else {
                    return nil
                }
            }
            self = result
        }
    }
    

    Example:

    let hexString = "A0"
    if let num = UInt(hexString, radix: 16) {
        println(num)
    } else {
        println("invalid input")
    }