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
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
If you have a string representation, "ff"
, you can use UInt8(_:radix:)
:
let string = "ff"
if let value = UInt8(string, radix: 16) {
print(value)
}
you can use the function strtoul to convert your hex to decimal:
let result = UInt8(strtoul("ff", nil, 16)) // 255
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
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.