我有一个HEX字符串d285,我想将其转换为UInt16,请指导我如何转换它。我试过这个
let buffer = UInt16("\(UInt8(text, radix: 16)!)")
return Data(bytes: (buffer?.bigEndian.toBytes)!)
但它无效
答案 0 :(得分:3)
UInt16有initializer,它取一个字符串和基数值。这可以用于从字符串创建UInt16。
let hexString = "d285"
let hexToInt = UInt16(hexString, radix: 16) // prints 53893
答案 1 :(得分:0)
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)!
希望这会对你有所帮助