24

Sorry if this seems really simple, I just can't find it anywhere online.

I have a UInt8 in hex, I need to get it to a decimal. How do I achieve this in swift?

For example:

"ff"

Thanks

JoeBayLD
  • 939
  • 2
  • 10
  • 25
  • 1
    possible duplicate of [How to convert hex number to bin in Swift?](http://stackoverflow.com/questions/26284223/how-to-convert-hex-number-to-bin-in-swift) – Amadan Feb 20 '15 at 03:41
  • (if by "decimal" you mean a true `UInt8` like `255`, and not another string with decimal representation, `"255"`). – Amadan Feb 20 '15 at 03:42
  • https://stackoverflow.com/q/45667905/3908884 – Meet Doshi Aug 14 '17 at 06:06

4 Answers4

53

If you have a string representation, "ff", you can use UInt8(_:radix:):

let string = "ff"
if let value = UInt8(string, radix: 16) {
    print(value)
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044
5

you can use the function strtoul to convert your hex to decimal:

let result = UInt8(strtoul("ff", nil, 16))  // 255
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • That works. One more thing. If I print my NSData it's . I can convert to string and remove the first and last character. But is that the best way to do it? – JoeBayLD Feb 20 '15 at 03:49
  • 2
    @JoeBayLD You do _not_ to get the string representation and then convert that to binary. Use `getBytes` to get the binary data directly. – Rob Feb 20 '15 at 03:55
  • Thanks @Rob I just found this and appears to be working. I'll post a new question of the final product to make sure it's most efficient. http://stackoverflow.com/questions/25424831/cant-covert-nsdata-to-nsstring-swift – JoeBayLD Feb 20 '15 at 04:00
5

Try this code, It's work for me.

// Hex to decimal

let h2 = "ff"
let d4 = Int(h2, radix: 16)!
print(d4) 

Hope this is help for some one

Jaywant Khedkar
  • 5,941
  • 2
  • 44
  • 55
4

If your HEX value is not a String, but just something you want to convert compile-time, you can also use:

let integer : UInt8 = 0xff

So prefixing it with 0x will do the job.

Aron K.
  • 250
  • 3
  • 8