4

how to convert hex to decimal in swift?

I have string "423fdf4dfb1115" and I need get this => 18647576781459733.

I try this:

let result = UInt8(strtoul("423fdf4dfb1115", nil, 16)) 

but app crash...

I use this online convert: http://www.binaryhexconverter.com/hex-to-decimal-converter

3
  • you need to loop through the string Commented Jun 14, 2016 at 20:07
  • 2
    Why are you casting the result to an UInt8? You've got a very large number there, it couldn't possibly fit in a tiny UInt8. Commented Jun 14, 2016 at 20:08
  • the HEX number you provided (423fdf4dfb1115) is 18,596,864,257,291,000. I proved this in excel (cell x 16^0 )and increment one additional for each digit AND summing the results for each. Commented May 1, 2017 at 14:12

2 Answers 2

10

The result must be UInt64 (UInt8.max is 255).

There is a convenience initializer, strtoul is not needed.

let string = "423fdf4dfb1115" let result = UInt64(string, radix:16) 
Sign up to request clarification or add additional context in comments.

2 Comments

Cool trick. I did not know about that initializer. Will it take ANY valid radix? (Base 37, even, if for some strange reason you wanted that?) And is there a corresponding method that outputs the value of an integer class as a string in a given radix?
@DuncanC I think so. Yes, String has similar initializers for example print(String(999_999, radix: 16)) // "f423f". There is even an optional uppercase parameter to get F423F.
2

let result = UInt64(strtoul("423fdf4dfb1115", nil, 16))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.