0

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?

1
  • Thank you for your suggestion :) Commented Sep 30, 2017 at 11:01

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Works flawlessly :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.