DanielD
DanielD

Reputation: 87

How to convert Hex to decimal in Swift 3? (self written code without third-party library and Foundation)

I am looking for a simple way to convert a Hex to decimal in Swift 3. For example, this code converts binary to decimal without any problems.

func convertToDecimal(binaryVal: String) -> String {

    var result: Int = 0

    for num in binaryVal {

        switch num {

        case "0": result = result * 2
        case "1": result = result * 2 + 1
        default: return "Error"

        }

    }

    return "\(result)"     
}

Maybe there is same workaround but only for Hex to decimal?

Upvotes: 0

Views: 202

Answers (1)

Istvan
Istvan

Reputation: 216

It should be the same, you just need to change what is inside the ‘for’ loop. So something like this would work:

result = result * 16 + numValue

where ‘numValue’ is the decimal value of ‘num’, so it is 10 for A, 11 for B, ... , 15 for F.

Upvotes: 1

Related Questions