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

时间:2017-10-09 10:18:07

标签: ios swift uint8t uint uint16

我有一个HEX字符串d285,我想将其转换为UInt16,请指导我如何转换它。我试过这个

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

但它无效

2 个答案:

答案 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)!
  

希望这会对你有所帮助