How to convert HEX string to UInt16?

2019-05-24 17:16发布

I have a HEX string d285 and I want to convert it UInt16, please guide me how I can convert it. I tried this

let buffer = UInt16("\(UInt8(text, radix: 16)!)")
return Data(bytes: (buffer?.bigEndian.toBytes)!)

but it's not working

2条回答
时光不老,我们不散
2楼-- · 2019-05-24 17:51

UInt16 has an initializer that takes a string and radix value. This can be used to create UInt16 from string.

let hexString = "d285"
let hexToInt = UInt16(hexString, radix: 16) // prints 53893
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-05-24 17:58
let hexStr = "d285"
var byteArr = [UInt8]()
byteArr += hexStr.utf8  // Convert into byte array

let str = NSString(bytes: byteArr, length: byteArr.count, encoding: String.Encoding.utf8.rawValue)
let number = UInt(str, radix: 16)!

Hope this will help you

查看更多
登录 后发表回答