如何将 HEX 字符串转换为 UInt16?

How to convert HEX string to UInt16?

我有一个十六进制字符串 d285,我想将它转换为 UInt16,请指导我如何转换它。我试过了

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

但它不起作用

UInt16 有一个 initializer 接受字符串和基数值。这可用于从字符串创建 UInt16。

let hexString = "d285"
let hexToInt = UInt16(hexString, radix: 16) // prints 53893
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