Daniel Dluzhnevsky Daniel Dluzhnevsky - 3 years ago 227
Swift Question

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download